<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Java8新特性总结 | 冰河技术</title>
    <meta name="generator" content="VuePress 1.9.7">
    <link rel="icon" href="/favicon.ico">
    <script charset="utf-8" async="async" src="/js/jquery.min.js"></script>
    <script charset="utf-8" async="async" src="/js/global.js"></script>
    <script charset="utf-8" async="async" src="/js/fingerprint2.min.js"></script>
    <script charset="utf-8" async="async" src="https://v1.cnzz.com/z_stat.php?id=1281063564&amp;web_id=1281063564"></script>
    <script charset="utf-8" async="async" src="https://s9.cnzz.com/z_stat.php?id=1281064551&amp;web_id=1281064551"></script>
    <script>
            var _hmt = _hmt || [];
            (function() {
              var hm = document.createElement("script");
              hm.src = "https://hm.baidu.com/hm.js?d091d2fd0231588b1d0f9231e24e3f5e";
              var s = document.getElementsByTagName("script")[0];
              s.parentNode.insertBefore(hm, s);
            })();
            </script>
    <meta name="description" content="包含：编程语言，开发技术，分布式，微服务，高并发，高可用，高可扩展，高可维护，JVM技术，MySQL，分布式数据库，分布式事务，云原生，大数据，云计算，渗透技术，各种面试题，面试技巧...">
    <meta property="article:modified_time" content="2022-05-23T11:30:51.000Z">
    <meta property="og:title" content="Java8新特性总结">
    <meta property="og:type" content="article">
    <meta property="og:url" content="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html">
    <meta name="twitter:title" content="Java8新特性总结">
    <meta name="twitter:url" content="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html">
    <meta name="twitter:card" content="summary_large_image">
    <meta name="robots" content="all">
    <meta name="author" content="冰河">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <meta name="keywords" content="冰河，冰河技术, 编程语言，开发技术，分布式，微服务，高并发，高可用，高可扩展，高可维护，JVM技术，MySQL，分布式数据库，分布式事务，云原生，大数据，云计算，渗透技术，各种面试题，面试技巧">
    <meta name="apple-mobile-web-app-capable" content="yes">
    
    <link rel="preload" href="/assets/css/0.styles.ab888ebb.css" as="style"><link rel="preload" href="/assets/css/styles.css?v=1653305936337" as="style"><link rel="preload" href="/assets/js/cg-styles.js?v=1653305936337" as="script"><link rel="preload" href="/assets/js/cg-app.js?v=1653305936337" as="script"><link rel="preload" href="/assets/js/cg-4.js?v=1653305936337" as="script"><link rel="preload" href="/assets/js/cg-3.js?v=1653305936337" as="script"><link rel="preload" href="/assets/js/cg-64.js?v=1653305936337" as="script"><link rel="preload" href="/assets/js/cg-5.js?v=1653305936337" as="script"><link rel="preload" href="/assets/js/cg-6.js?v=1653305936337" as="script">
    <link rel="stylesheet" href="/assets/css/0.styles.ab888ebb.css"><link rel="stylesheet" href="/assets/css/styles.css?v=1653305936337">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><!----> <span class="site-name">冰河技术</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/md/other/guide-to-reading.html" class="nav-link">
  导读
</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="核心技术" class="dropdown-title"><span class="title">核心技术</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>
          Java核心技术
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/core/java/basics/2022-04-28-全网最全正则表达式总结.html" class="nav-link">
  Java基础
</a></li><li class="dropdown-subitem"><a href="/md/core/java/advanced/default.html" class="nav-link">
  Java进阶
</a></li><li class="dropdown-subitem"><a href="/md/core/java/senior/default.html" class="nav-link">
  Java高级
</a></li><li class="dropdown-subitem"><a href="/md/core/java/java8/2022-03-31-001-Java8有哪些新特性呢？.html" class="nav-link">
  Java8新特性
</a></li></ul></li><li class="dropdown-item"><h4>
          Spring核心技术
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/core/spring/ioc/2022-04-04-001-聊聊Spring注解驱动开发那些事儿.html" class="nav-link">
  IOC核心技术
</a></li><li class="dropdown-subitem"><a href="/md/core/spring/aop/default.html" class="nav-link">
  AOP核心技术
</a></li></ul></li><li class="dropdown-item"><h4>
          JVM核心技术
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/core/jvm/2022-04-18-001-JVM调优的几种场景.html" class="nav-link">
  JVM调优技术
</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="性能调优" class="dropdown-title"><span class="title">性能调优</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/performance/jvm/default.html" class="nav-link">
  JVM性能调优
</a></li><li class="dropdown-item"><!----> <a href="/md/performance/tomcat/default.html" class="nav-link">
  Tomcat性能调优
</a></li><li class="dropdown-item"><!----> <a href="/md/performance/mysql/default.html" class="nav-link">
  MySQL性能调优
</a></li><li class="dropdown-item"><!----> <a href="/md/performance/system/default.html" class="nav-link">
  操作系统性能调优
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="并发编程" class="dropdown-title"><span class="title">并发编程</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/concurrent/bottom/default.html" class="nav-link">
  底层技术
</a></li><li class="dropdown-item"><!----> <a href="/md/concurrent/source/2020-03-30-001-一文搞懂线程与多线程.html" class="nav-link">
  源码分析
</a></li><li class="dropdown-item"><!----> <a href="/md/concurrent/basics/2020-03-30-001-明明中断了线程，却为何不起作用呢？.html" class="nav-link">
  基础案例
</a></li><li class="dropdown-item"><!----> <a href="/md/concurrent/ActualCombat/default.html" class="nav-link">
  实战案例
</a></li><li class="dropdown-item"><!----> <a href="/md/concurrent/interview/default.html" class="nav-link">
  面试
</a></li><li class="dropdown-item"><!----> <a href="/md/concurrent/framework/default.html" class="nav-link">
  系统架构
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="框架源码" class="dropdown-title"><span class="title">框架源码</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/frame/spring/default.html" class="nav-link">
  Spring源码
</a></li><li class="dropdown-item"><!----> <a href="/md/frame/springmvc/default.html" class="nav-link">
  SpringMVC源码
</a></li><li class="dropdown-item"><!----> <a href="/md/frame/mybatis/default.html" class="nav-link">
  MyBatis源码
</a></li><li class="dropdown-item"><!----> <a href="/md/frame/dubbo/default.html" class="nav-link">
  Dubbo源码
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="分布式" class="dropdown-title"><span class="title">分布式</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>
          缓存技术
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/cache/default.html" class="nav-link">
  Redis
</a></li></ul></li><li class="dropdown-item"><h4>
          服务注册发现
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/zookeeper/default.html" class="nav-link">
  Zookeeper
</a></li></ul></li><li class="dropdown-item"><h4>
          消息中间件
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/mq/rabbitmq/default.html" class="nav-link">
  RabbitMQ
</a></li><li class="dropdown-subitem"><a href="/md/distributed/mq/rocketmq/default.html" class="nav-link">
  RocketMQ
</a></li><li class="dropdown-subitem"><a href="/md/distributed/mq/kafka/default.html" class="nav-link">
  Kafka
</a></li></ul></li><li class="dropdown-item"><h4>
          网络通信
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/netty/default.html" class="nav-link">
  Netty
</a></li></ul></li><li class="dropdown-item"><h4>
          远程调用
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/dubbo/default.html" class="nav-link">
  Dubbo
</a></li></ul></li><li class="dropdown-item"><h4>
          数据库
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/mongodb/default.html" class="nav-link">
  MongoDB
</a></li></ul></li><li class="dropdown-item"><h4>
          搜索引擎
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/es/default.html" class="nav-link">
  ElasticSearch
</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="微服务" class="dropdown-title"><span class="title">微服务</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/microservices/springboot/default.html" class="nav-link">
  SpringBoot
</a></li><li class="dropdown-item"><!----> <a href="/md/microservices/springcloudalibaba/2022-04-02-SpringCloudAlibaba专栏开篇.html" class="nav-link">
  SpringCloudAlibaba
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="中间件" class="dropdown-title"><span class="title">中间件</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/middleware/bytecode/2022-04-11-001-工作多年的你依然重复做着CRUD-是否接触过这种技术.html" class="nav-link">
  字节码编程
</a></li><li class="dropdown-item"><!----> <a href="/md/middleware/threadpool/default.html" class="nav-link">
  手写线程池
</a></li><li class="dropdown-item"><!----> <a href="/md/middleware/limiter/default.html" class="nav-link">
  分布式限流
</a></li><li class="dropdown-item"><!----> <a href="/md/middleware/independent/default.html" class="nav-link">
  开源项目
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="项目实战" class="dropdown-title"><span class="title">项目实战</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/microservices/springcloudalibaba/2022-04-02-SpringCloudAlibaba专栏开篇.html" class="nav-link">
  SpringCloud Alibaba实战
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="渗透技术" class="dropdown-title"><span class="title">渗透技术</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/hack/environment/2022-04-17-001-安装Kali系统.html" class="nav-link">
  基础环境篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/tools/2022-04-17-001-使用Easy-Creds工具攻击无线网络.html" class="nav-link">
  渗透工具篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/horse/2022-05-02-001-各种一句话木马大全.html" class="nav-link">
  木马篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/sql/2022-05-02-001-sqli-labs-master下载与安装.html" class="nav-link">
  SQL注入篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/shell/2022-05-02-001-各种解析漏洞拿shell.html" class="nav-link">
  漏洞拿Shell篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/crack/2022-05-02-001-使用rarcrack暴力破解RAR-ZIP-7Z压缩包.html" class="nav-link">
  暴力破解篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/bash/2022-05-02-001-3389脚本开启代码(vbs版).html" class="nav-link">
  渗透脚本篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/raising/2022-05-02-001-数据库提权.html" class="nav-link">
  数据与系统提权篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/client/2022-05-02-001-浏览器渗透.html" class="nav-link">
  客户端渗透篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/sociology/2022-05-02-001-Metasploit之社会工程学工具包.html" class="nav-link">
  社会工程学
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/question/2022-05-02-001-HTTP错误4031禁止访问-执行访问被拒绝.html" class="nav-link">
  问题记录篇
</a></li></ul></div></div><div class="nav-item"><a href="/md/interview/2022-04-18-001-面试必问-聊聊JVM性能调优.html" class="nav-link">
  面试必问系列
</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="📚PDF" class="dropdown-title"><span class="title">📚PDF</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>
          出版图书
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/knowledge/book/2022-03-29-深入理解分布式事务.html" class="nav-link">
  《深入理解分布式事务：原理与实战》
</a></li><li class="dropdown-subitem"><a href="/md/knowledge/book/2022-03-29-MySQL技术大全.html" class="nav-link">
  《MySQL技术大全：开发、优化与运维实战》
</a></li><li class="dropdown-subitem"><a href="/md/knowledge/book/2022-03-29-海量数据处理与大数据技术实战.html" class="nav-link">
  《海量数据处理与大数据技术实战》
</a></li></ul></li><li class="dropdown-item"><h4>
          电子书籍
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/knowledge/pdf/2022-03-30-《冰河的渗透实战笔记》电子书，442页，37万字，正式发布.html" class="nav-link">
  冰河的渗透实战笔记
</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="关于" class="dropdown-title"><span class="title">关于</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/about/me/about-me.html" class="nav-link">
  关于自己
</a></li><li class="dropdown-item"><!----> <a href="/md/about/study/default.html" class="nav-link">
  关于学习
</a></li><li class="dropdown-item"><!----> <a href="/md/about/job/default.html" class="nav-link">
  关于职场
</a></li></ul></div></div><div class="nav-item"><a href="https://space.bilibili.com/517638832" target="_blank" rel="noopener noreferrer" class="nav-link external">
  B站
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div><div class="nav-item"><a href="https://github.com/binghe001/BingheGuide" target="_blank" rel="noopener noreferrer" class="nav-link external">
  Github
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <!----></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/md/other/guide-to-reading.html" class="nav-link">
  导读
</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="核心技术" class="dropdown-title"><span class="title">核心技术</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>
          Java核心技术
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/core/java/basics/2022-04-28-全网最全正则表达式总结.html" class="nav-link">
  Java基础
</a></li><li class="dropdown-subitem"><a href="/md/core/java/advanced/default.html" class="nav-link">
  Java进阶
</a></li><li class="dropdown-subitem"><a href="/md/core/java/senior/default.html" class="nav-link">
  Java高级
</a></li><li class="dropdown-subitem"><a href="/md/core/java/java8/2022-03-31-001-Java8有哪些新特性呢？.html" class="nav-link">
  Java8新特性
</a></li></ul></li><li class="dropdown-item"><h4>
          Spring核心技术
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/core/spring/ioc/2022-04-04-001-聊聊Spring注解驱动开发那些事儿.html" class="nav-link">
  IOC核心技术
</a></li><li class="dropdown-subitem"><a href="/md/core/spring/aop/default.html" class="nav-link">
  AOP核心技术
</a></li></ul></li><li class="dropdown-item"><h4>
          JVM核心技术
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/core/jvm/2022-04-18-001-JVM调优的几种场景.html" class="nav-link">
  JVM调优技术
</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="性能调优" class="dropdown-title"><span class="title">性能调优</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/performance/jvm/default.html" class="nav-link">
  JVM性能调优
</a></li><li class="dropdown-item"><!----> <a href="/md/performance/tomcat/default.html" class="nav-link">
  Tomcat性能调优
</a></li><li class="dropdown-item"><!----> <a href="/md/performance/mysql/default.html" class="nav-link">
  MySQL性能调优
</a></li><li class="dropdown-item"><!----> <a href="/md/performance/system/default.html" class="nav-link">
  操作系统性能调优
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="并发编程" class="dropdown-title"><span class="title">并发编程</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/concurrent/bottom/default.html" class="nav-link">
  底层技术
</a></li><li class="dropdown-item"><!----> <a href="/md/concurrent/source/2020-03-30-001-一文搞懂线程与多线程.html" class="nav-link">
  源码分析
</a></li><li class="dropdown-item"><!----> <a href="/md/concurrent/basics/2020-03-30-001-明明中断了线程，却为何不起作用呢？.html" class="nav-link">
  基础案例
</a></li><li class="dropdown-item"><!----> <a href="/md/concurrent/ActualCombat/default.html" class="nav-link">
  实战案例
</a></li><li class="dropdown-item"><!----> <a href="/md/concurrent/interview/default.html" class="nav-link">
  面试
</a></li><li class="dropdown-item"><!----> <a href="/md/concurrent/framework/default.html" class="nav-link">
  系统架构
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="框架源码" class="dropdown-title"><span class="title">框架源码</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/frame/spring/default.html" class="nav-link">
  Spring源码
</a></li><li class="dropdown-item"><!----> <a href="/md/frame/springmvc/default.html" class="nav-link">
  SpringMVC源码
</a></li><li class="dropdown-item"><!----> <a href="/md/frame/mybatis/default.html" class="nav-link">
  MyBatis源码
</a></li><li class="dropdown-item"><!----> <a href="/md/frame/dubbo/default.html" class="nav-link">
  Dubbo源码
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="分布式" class="dropdown-title"><span class="title">分布式</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>
          缓存技术
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/cache/default.html" class="nav-link">
  Redis
</a></li></ul></li><li class="dropdown-item"><h4>
          服务注册发现
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/zookeeper/default.html" class="nav-link">
  Zookeeper
</a></li></ul></li><li class="dropdown-item"><h4>
          消息中间件
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/mq/rabbitmq/default.html" class="nav-link">
  RabbitMQ
</a></li><li class="dropdown-subitem"><a href="/md/distributed/mq/rocketmq/default.html" class="nav-link">
  RocketMQ
</a></li><li class="dropdown-subitem"><a href="/md/distributed/mq/kafka/default.html" class="nav-link">
  Kafka
</a></li></ul></li><li class="dropdown-item"><h4>
          网络通信
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/netty/default.html" class="nav-link">
  Netty
</a></li></ul></li><li class="dropdown-item"><h4>
          远程调用
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/dubbo/default.html" class="nav-link">
  Dubbo
</a></li></ul></li><li class="dropdown-item"><h4>
          数据库
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/mongodb/default.html" class="nav-link">
  MongoDB
</a></li></ul></li><li class="dropdown-item"><h4>
          搜索引擎
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/distributed/es/default.html" class="nav-link">
  ElasticSearch
</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="微服务" class="dropdown-title"><span class="title">微服务</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/microservices/springboot/default.html" class="nav-link">
  SpringBoot
</a></li><li class="dropdown-item"><!----> <a href="/md/microservices/springcloudalibaba/2022-04-02-SpringCloudAlibaba专栏开篇.html" class="nav-link">
  SpringCloudAlibaba
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="中间件" class="dropdown-title"><span class="title">中间件</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/middleware/bytecode/2022-04-11-001-工作多年的你依然重复做着CRUD-是否接触过这种技术.html" class="nav-link">
  字节码编程
</a></li><li class="dropdown-item"><!----> <a href="/md/middleware/threadpool/default.html" class="nav-link">
  手写线程池
</a></li><li class="dropdown-item"><!----> <a href="/md/middleware/limiter/default.html" class="nav-link">
  分布式限流
</a></li><li class="dropdown-item"><!----> <a href="/md/middleware/independent/default.html" class="nav-link">
  开源项目
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="项目实战" class="dropdown-title"><span class="title">项目实战</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/microservices/springcloudalibaba/2022-04-02-SpringCloudAlibaba专栏开篇.html" class="nav-link">
  SpringCloud Alibaba实战
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="渗透技术" class="dropdown-title"><span class="title">渗透技术</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/hack/environment/2022-04-17-001-安装Kali系统.html" class="nav-link">
  基础环境篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/tools/2022-04-17-001-使用Easy-Creds工具攻击无线网络.html" class="nav-link">
  渗透工具篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/horse/2022-05-02-001-各种一句话木马大全.html" class="nav-link">
  木马篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/sql/2022-05-02-001-sqli-labs-master下载与安装.html" class="nav-link">
  SQL注入篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/shell/2022-05-02-001-各种解析漏洞拿shell.html" class="nav-link">
  漏洞拿Shell篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/crack/2022-05-02-001-使用rarcrack暴力破解RAR-ZIP-7Z压缩包.html" class="nav-link">
  暴力破解篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/bash/2022-05-02-001-3389脚本开启代码(vbs版).html" class="nav-link">
  渗透脚本篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/raising/2022-05-02-001-数据库提权.html" class="nav-link">
  数据与系统提权篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/client/2022-05-02-001-浏览器渗透.html" class="nav-link">
  客户端渗透篇
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/sociology/2022-05-02-001-Metasploit之社会工程学工具包.html" class="nav-link">
  社会工程学
</a></li><li class="dropdown-item"><!----> <a href="/md/hack/question/2022-05-02-001-HTTP错误4031禁止访问-执行访问被拒绝.html" class="nav-link">
  问题记录篇
</a></li></ul></div></div><div class="nav-item"><a href="/md/interview/2022-04-18-001-面试必问-聊聊JVM性能调优.html" class="nav-link">
  面试必问系列
</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="📚PDF" class="dropdown-title"><span class="title">📚PDF</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>
          出版图书
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/knowledge/book/2022-03-29-深入理解分布式事务.html" class="nav-link">
  《深入理解分布式事务：原理与实战》
</a></li><li class="dropdown-subitem"><a href="/md/knowledge/book/2022-03-29-MySQL技术大全.html" class="nav-link">
  《MySQL技术大全：开发、优化与运维实战》
</a></li><li class="dropdown-subitem"><a href="/md/knowledge/book/2022-03-29-海量数据处理与大数据技术实战.html" class="nav-link">
  《海量数据处理与大数据技术实战》
</a></li></ul></li><li class="dropdown-item"><h4>
          电子书籍
        </h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/md/knowledge/pdf/2022-03-30-《冰河的渗透实战笔记》电子书，442页，37万字，正式发布.html" class="nav-link">
  冰河的渗透实战笔记
</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="关于" class="dropdown-title"><span class="title">关于</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/md/about/me/about-me.html" class="nav-link">
  关于自己
</a></li><li class="dropdown-item"><!----> <a href="/md/about/study/default.html" class="nav-link">
  关于学习
</a></li><li class="dropdown-item"><!----> <a href="/md/about/job/default.html" class="nav-link">
  关于职场
</a></li></ul></div></div><div class="nav-item"><a href="https://space.bilibili.com/517638832" target="_blank" rel="noopener noreferrer" class="nav-link external">
  B站
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div><div class="nav-item"><a href="https://github.com/binghe001/BingheGuide" target="_blank" rel="noopener noreferrer" class="nav-link external">
  Github
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <!----></nav>  <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>Java基础</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/md/core/java/basics/2022-04-28-全网最全正则表达式总结.html" class="sidebar-link">全网最全正则表达式总结</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>Java进阶</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/md/core/java/advanced/default.html" class="sidebar-link">关于我</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>Java高级</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/md/core/java/senior/default.html" class="sidebar-link">关于我</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span>Java8新特性</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/md/core/java/java8/2022-03-31-001-Java8有哪些新特性呢？.html" class="sidebar-link">一张图带你领略Java8有哪些新特性</a></li><li><a href="/md/core/java/java8/2022-03-31-002-你知道Java8为什么引入Lambda表达式吗.html" class="sidebar-link">你知道Java8为什么要引入Lambda表达式吗？</a></li><li><a href="/md/core/java/java8/2022-03-31-003-Lambda表达式基础语法，都在这儿了.html" class="sidebar-link">Lambda表达式基础语法，都在这儿了！！</a></li><li><a href="/md/core/java/java8/2022-03-31-004-Lambda表达式典型案例，你想要的的都在这儿了.html" class="sidebar-link">Lambda表达式典型案例，你想要的的都在这儿了！！</a></li><li><a href="/md/core/java/java8/2022-03-31-005-一文搞懂函数式接口.html" class="sidebar-link">一文搞懂函数式接口</a></li><li><a href="/md/core/java/java8/2022-03-31-006-知识点总结，你都会了吗.html" class="sidebar-link">知识点总结，你都会了吗？</a></li><li><a href="/md/core/java/java8/2022-03-31-007-方法引用和构造器引用.html" class="sidebar-link">浅谈方法引用和构造器引用</a></li><li><a href="/md/core/java/java8/2022-03-31-008-关于Java8的Stream API,都在这儿了.html" class="sidebar-link">关于Java8的Stream API,都在这儿了</a></li><li><a href="/md/core/java/java8/2022-03-31-009-强大的Stream API，你了解吗.html" class="sidebar-link">强大的Stream API，你了解吗</a></li><li><a href="/md/core/java/java8/2022-03-31-010-Stream API有哪些中间操作,看完你也可以吊打面试官.html" class="sidebar-link">Stream API有哪些中间操作？看完你也可以吊打面试官！！</a></li><li><a href="/md/core/java/java8/2022-03-31-011-Java8中的Stream API有哪些终止操作.html" class="sidebar-link">Java8中的Stream API有哪些终止操作</a></li><li><a href="/md/core/java/java8/2022-03-31-012-关于并行流与串行流，你必须掌握这些.html" class="sidebar-link">关于并行流与串行流，你必须掌握这些！！</a></li><li><a href="/md/core/java/java8/2022-03-31-013-不了解Optional类，简历上别说你懂Java8.html" class="sidebar-link">不了解Optional类，简历上别说你懂Java8</a></li><li><a href="/md/core/java/java8/2022-03-31-014-接口中的默认方法和静态方法，你都掌握了吗.html" class="sidebar-link">接口中的默认方法和静态方法，你都掌握了吗？</a></li><li><a href="/md/core/java/java8/2022-03-31-015-关于Java8中的日期时间API，你需要掌握这些.html" class="sidebar-link">关于Java8中的日期时间API，你需要掌握这些！！</a></li><li><a href="/md/core/java/java8/2022-03-31-016-重复注解与类型注解，你真的学会了吗.html" class="sidebar-link">重复注解与类型注解，你真的学会了吗？</a></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8新特性总结.html" class="active sidebar-link">Java8新特性总结</a></li></ul></section></li></ul> </aside> <div><main class="page"> <div class="theme-default-content content__default"><h1 id="java8新特性总结"><a href="#java8新特性总结" class="header-anchor">#</a> Java8新特性总结</h1> <p><strong>大家好，我是冰河~~</strong></p> <p>说实话，肝这篇文章花了我一个月的时间，关于Java8的新特性全在这儿了，<strong>建议先收藏后阅读</strong>。</p> <h2 id="java8有哪些新特性"><a href="#java8有哪些新特性" class="header-anchor">#</a> Java8有哪些新特性？</h2> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194006889.jpg" loading="lazy" class="lazy"></p> <p><strong>简单来说，Java8新特性如下所示：</strong></p> <ul><li><p>Lambda表达式</p></li> <li><p>函数式接口</p></li> <li><p>方法引用与构造器引用</p></li> <li><p>Stream API</p></li> <li><p>接口的默认方法与静态方法</p></li> <li><p>新时间日期API</p></li> <li><p>其他新特性</p></li></ul> <p>其中，引用最广泛的新特性是Lambda表达式和Stream API。</p> <h2 id="java8有哪些优点"><a href="#java8有哪些优点" class="header-anchor">#</a> Java8有哪些优点？</h2> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194017939.jpg" loading="lazy" class="lazy"></p> <p><strong>简单来说Java8优点如下所示。</strong></p> <ul><li>速度更快</li> <li>代码更少（增加了新的语法Lambda表达式）</li> <li>强大的Stream API</li> <li>便于并行</li> <li>最大化减少空指针异常Optional</li></ul> <h2 id="lambda表达式"><a href="#lambda表达式" class="header-anchor">#</a> Lambda表达式</h2> <h3 id="什么是lambda表达式"><a href="#什么是lambda表达式" class="header-anchor">#</a> 什么是Lambda表达式？</h3> <p>Lambda表达式是一个匿名函数，我们可以这样理解Lambda表达式：Lambda是一段可以传递的代码（能够做到将代码像数据一样进行传递）。使用Lambda表达式能够写出更加简洁、灵活的代码。并且，使用Lambda表达式能够使Java的语言表达能力得到提升。</p> <h3 id="匿名内部类"><a href="#匿名内部类" class="header-anchor">#</a> 匿名内部类</h3> <p>在介绍如何使用Lambda表达式之前，我们先来看看匿名内部类，例如，我们使用匿名内部类比较两个Integer类型数据的大小。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> com <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">compare</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> o1<span class="token punctuation">,</span> <span class="token class-name">Integer</span> o2<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>o1<span class="token punctuation">,</span> o2<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>在上述代码中，我们使用匿名内部类实现了比较两个Integer类型数据的大小。</p> <p>接下来，我们就可以将上述匿名内部类的实例作为参数，传递到其他方法中了，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code> <span class="token class-name">TreeSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> treeSet <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TreeSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span>com<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>完整的代码如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> com <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">compare</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> o1<span class="token punctuation">,</span> <span class="token class-name">Integer</span> o2<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>o1<span class="token punctuation">,</span> o2<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token class-name">TreeSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> treeSet <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TreeSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span>com<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p>我们分析下上述代码，在整个匿名内部类中，实际上真正有用的就是下面一行代码。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code> <span class="token keyword">return</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>o1<span class="token punctuation">,</span> o2<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>其他的代码本质上都是“冗余”的。但是为了书写上面的一行代码，我们不得不在匿名内部类中书写更多的代码。</p> <h3 id="lambda表达式-2"><a href="#lambda表达式-2" class="header-anchor">#</a> Lambda表达式</h3> <p>如果使用Lambda表达式完成两个Integer类型数据的比较，我们该如何实现呢？</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> com <span class="token operator">=</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>看到没，使用Lambda表达式，我们只需要使用一行代码就能够实现两个Integer类型数据的比较。</p> <p>我们也可以将Lambda表达式传递到TreeSet的构造方法中，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code> <span class="token class-name">TreeSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> treeSet <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TreeSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>直观的感受就是使用Lambda表达式一行代码就能搞定匿名内部类多行代码的功能。</p> <p><strong>看到这，不少读者会问：我使用匿名内部类的方式实现比较两个整数类型的数据大小并不复杂啊！我为啥还要学习一种新的语法呢？</strong></p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194150700.jpg" loading="lazy" class="lazy"></p> <p>其实，我想说的是：上面咱们只是简单的列举了一个示例，接下来，咱们写一个稍微复杂一点的例子，来对比下使用匿名内部类与Lambda表达式哪种方式更加简洁。</p> <h3 id="对比常规方法和lambda表达式"><a href="#对比常规方法和lambda表达式" class="header-anchor">#</a> 对比常规方法和Lambda表达式</h3> <p>例如，现在有这样一个需求：<strong>获取当前公司中员工年龄大于30岁的员工信息。</strong></p> <p>首先，我们需要创建一个Employee实体类来存储员工的信息。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Data</span>
<span class="token annotation punctuation">@Builder</span>
<span class="token annotation punctuation">@ToString</span>
<span class="token annotation punctuation">@NoArgsConstructor</span>
<span class="token annotation punctuation">@AllArgsConstructor</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Employee</span> <span class="token keyword">implements</span> <span class="token class-name">Serializable</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">long</span> serialVersionUID <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">9079722457749166858L</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> name<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">Integer</span> age<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">Double</span> salary<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p>在Employee中，我们简单存储了员工的姓名、年龄和薪资。</p> <p>接下来，我们创建一个存储多个员工的List集合，如下所示。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>protected List<span class="token operator">&lt;</span>Employee<span class="token operator">&gt;</span> employees <span class="token operator">=</span> Arrays.asList<span class="token punctuation">(</span>
		new Employee<span class="token punctuation">(</span><span class="token string">&quot;张三&quot;</span>, <span class="token number">18</span>, <span class="token number">9999.99</span><span class="token punctuation">)</span>,
		new Employee<span class="token punctuation">(</span><span class="token string">&quot;李四&quot;</span>, <span class="token number">38</span>, <span class="token number">5555.55</span><span class="token punctuation">)</span>,
		new Employee<span class="token punctuation">(</span><span class="token string">&quot;王五&quot;</span>, <span class="token number">60</span>, <span class="token number">6666.66</span><span class="token punctuation">)</span>,
		new Employee<span class="token punctuation">(</span><span class="token string">&quot;赵六&quot;</span>, <span class="token number">16</span>, <span class="token number">7777.77</span><span class="token punctuation">)</span>,
		new Employee<span class="token punctuation">(</span><span class="token string">&quot;田七&quot;</span>, <span class="token number">18</span>, <span class="token number">3333.33</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p><strong>1.常规遍历集合</strong></p> <p>我们先使用常规遍历集合的方式来查找年龄大于等于30的员工信息。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> <span class="token function">filterEmployeesByAge</span><span class="token punctuation">(</span><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> list<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> employees <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span><span class="token punctuation">(</span><span class="token class-name">Employee</span> e <span class="token operator">:</span> list<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>e<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">30</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            employees<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> employees<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><p>接下来，我们测试一下上面的方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test3</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> employeeList <span class="token operator">=</span> <span class="token function">filterEmployeesByAge</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>employees<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Employee</span> e <span class="token operator">:</span> employeeList<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>运行test3方法，输出信息如下所示。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>李四, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">38</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">5555.55</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>王五, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">60</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">6666.66</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>总体来说，查找年龄大于或者等于30的员工信息，使用常规遍历集合的方式稍显复杂了。</p> <p>例如，<strong>需求发生了变化：获取当前公司中员工工资大于或者等于5000的员工信息。</strong></p> <p>此时，我们不得不再次创建一个按照工资过滤的方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> <span class="token function">filterEmployeesBySalary</span><span class="token punctuation">(</span><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> list<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> employees <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span><span class="token punctuation">(</span><span class="token class-name">Employee</span> e <span class="token operator">:</span> list<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>e<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">5000</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            employees<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> employees<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><p>对比filterEmployeesByAge()方法和filterEmployeesBySalary方法后，我们发现，大部分的方法体是相同的，只是for循环中对于条件的判断不同。</p> <p>如果此时我们再来一个需求，<strong>查找当前公司中年龄小于或者等于20的员工信息，那我们又要创建一个过滤方法了。</strong> 看来使用常规方法是真的不方便啊！</p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194229886.jpg#pic_center" loading="lazy" class="lazy"></p> <p>这里，问大家一个问题：对于这种常规方法最好的优化方式是啥？相信有不少小伙伴会说：将公用的方法抽取出来。没错，将公用的方法抽取出来是一种优化方式，但它不是最好的方式。最好的方式是啥？那就是使用 <strong>设计模式</strong> 啊！设计模式可是无数前辈不断实践而总结出的设计原则和设计模式。大家可以查看《<a href="https://mp.weixin.qq.com/s?__biz=Mzg4MjU0OTM1OA==&amp;mid=2247489408&amp;idx=1&amp;sn=84c48c9c3707691bd7709ebec66e82f1&amp;source=41#wechat_redirect" target="_blank" rel="noopener noreferrer">设计模式汇总——你需要掌握的23种设计模式都在这儿了！<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>》一文来学习设计模式专题。</p> <p><strong>2.使用设计模式优化代码</strong></p> <p>如何使用设计模式来优化上面的方法呢，大家继续往下看，对于设计模式不熟悉的同学可以先根据《<a href="https://mp.weixin.qq.com/s?__biz=Mzg4MjU0OTM1OA==&amp;mid=2247489408&amp;idx=1&amp;sn=84c48c9c3707691bd7709ebec66e82f1&amp;source=41#wechat_redirect" target="_blank" rel="noopener noreferrer">设计模式汇总——你需要掌握的23种设计模式都在这儿了！<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>》来学习。</p> <p>我们先定义一个泛型接口MyPredicate，对传递过来的数据进行过滤，符合规则返回true，不符合规则返回false。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">MyPredicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>

    <span class="token comment">/**
     * 对传递过来的T类型的数据进行过滤
     * 符合规则返回true，不符合规则返回false
     */</span>
    <span class="token keyword">boolean</span> <span class="token function">filter</span><span class="token punctuation">(</span><span class="token class-name">T</span> t<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>接下来，我们创建MyPredicate接口的实现类FilterEmployeeByAge来过滤年龄大于或者等于30的员工信息。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">FilterEmployeeByAge</span> <span class="token keyword">implements</span> <span class="token class-name">MyPredicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">filter</span><span class="token punctuation">(</span><span class="token class-name">Employee</span> employee<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> employee<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">30</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>我们定义一个过滤员工信息的方法，此时传递的参数不仅有员工的信息集合，同时还有一个我们定义的接口实例，在遍历员工集合时将符合过滤条件的员工信息返回。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">//优化方式一</span>
<span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> <span class="token function">filterEmployee</span><span class="token punctuation">(</span><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> list<span class="token punctuation">,</span> <span class="token class-name">MyPredicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> myPredicate<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> employees <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span><span class="token punctuation">(</span><span class="token class-name">Employee</span> e <span class="token operator">:</span> list<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>myPredicate<span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            employees<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> employees<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p>接下来，我们写一个测试方法来测试优化后的代码。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test4</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> employeeList <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">filterEmployee</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>employees<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">FilterEmployeeByAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Employee</span> e <span class="token operator">:</span> employeeList<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>运行test4()方法，输出的结果信息如下所示。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>李四, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">38</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">5555.55</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>王五, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">60</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">6666.66</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>写到这里，大家是否有一种豁然开朗的感觉呢？</p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194243730.jpg" loading="lazy" class="lazy"></p> <p>没错，这就是设计模式的魅力，对于设计模式不熟悉的小伙伴，一定要参照《<a href="https://mp.weixin.qq.com/s?__biz=Mzg4MjU0OTM1OA==&amp;mid=2247489408&amp;idx=1&amp;sn=84c48c9c3707691bd7709ebec66e82f1&amp;source=41#wechat_redirect" target="_blank" rel="noopener noreferrer">设计模式汇总——你需要掌握的23种设计模式都在这儿了！<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>》来学习。</p> <p>我们继续获取当前公司中工资大于或者等于5000的员工信息，此时，我们只需要创建一个FilterEmployeeBySalary类实现MyPredicate接口，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">FilterEmployeeBySalary</span> <span class="token keyword">implements</span> <span class="token class-name">MyPredicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">filter</span><span class="token punctuation">(</span><span class="token class-name">Employee</span> employee<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> employee<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">5000</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>接下来，就可以直接写测试方法了，在测试方法中继续调用<code>filterEmployee(List&lt;Employee&gt; list, MyPredicate&lt;Employee&gt; myPredicate)</code>方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test5</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> employeeList <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">filterEmployee</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>employees<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">FilterEmployeeBySalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Employee</span> e <span class="token operator">:</span> employeeList<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>运行test5方法，输出的结果信息如下所示。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>张三, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">18</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">9999.99</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>李四, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">38</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">5555.55</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>王五, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">60</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">6666.66</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>赵六, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">16</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">7777.77</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>可以看到，使用设计模式对代码进行优化后，无论过滤员工信息的需求如何变化，我们只需要创建MyPredicate接口的实现类来实现具体的过滤逻辑，然后在测试方法中调用<code>filterEmployee(List&lt;Employee&gt; list, MyPredicate&lt;Employee&gt; myPredicate)</code>方法将员工集合和过滤规则传入即可。</p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194306107.jpg" loading="lazy" class="lazy"></p> <p>这里，问大家一个问题：上面优化代码使用的设计模式是哪种设计模式呢？如果是你，你会想到使用设计模式来优化自己的代码吗？小伙伴们自己先思考一下到底使用的设计模式是什么？<strong>文末我会给出答案！</strong></p> <p>使用设计模式优化代码也有不好的地方：每次定义一个过滤策略的时候，我们都要单独创建一个过滤类！！</p> <p><strong>3.匿名内部类</strong></p> <p>那使用匿名内部类是不是能够优化我们书写的代码呢，接下来，我们就使用匿名内部类来实现对员工信息的过滤。先来看过滤年龄大于或者等于30的员工信息。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test6</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> employeeList <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">filterEmployee</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>employees<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">MyPredicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">filter</span><span class="token punctuation">(</span><span class="token class-name">Employee</span> employee<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> employee<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">30</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Employee</span> e <span class="token operator">:</span> employeeList<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p>运行test6方法，输出如下结果信息。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>李四, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">38</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">5555.55</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>王五, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">60</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">6666.66</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>再实现过滤工资大于或者等于5000的员工信息，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test7</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> employeeList <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">filterEmployee</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>employees<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">MyPredicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">filter</span><span class="token punctuation">(</span><span class="token class-name">Employee</span> employee<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> employee<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">5000</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Employee</span> e <span class="token operator">:</span> employeeList<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p>运行test7方法，输出如下结果信息。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>张三, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">18</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">9999.99</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>李四, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">38</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">5555.55</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>王五, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">60</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">6666.66</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>赵六, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">16</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">7777.77</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>匿名内部类看起来比常规遍历集合的方法要简单些，并且将使用设计模式优化代码时，每次创建一个类来实现过滤规则写到了匿名内部类中，使得代码进一步简化了。</p> <p>但是，使用匿名内部类代码的可读性不高，并且冗余代码也比较多！！</p> <p><strong>那还有没有更加简化的方式呢？</strong></p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/2021031419431791.jpg#pic_center" loading="lazy" class="lazy"></p> <p><strong>4.重头戏：Lambda表达式</strong></p> <p>在使用Lambda表达式时，我们还是要调用之前写的<code>filterEmployee(List&lt;Employee&gt; list, MyPredicate&lt;Employee&gt; myPredicate)</code>方法。</p> <p>注意看，获取年龄大于或者等于30的员工信息。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test8</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token function">filterEmployee</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>employees<span class="token punctuation">,</span> <span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> e<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">30</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>看到没，使用Lambda表达式只需要一行代码就完成了员工信息的过滤和输出。是不是很6呢。</p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/202103141943346.jpg#pic_center" loading="lazy" class="lazy"></p> <p>运行test8方法，输出如下的结果信息。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>李四, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">38</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">5555.55</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>王五, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">60</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">6666.66</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>再来看使用Lambda表达式来获取工资大于或者等于5000的员工信息，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test9</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token function">filterEmployee</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>employees<span class="token punctuation">,</span> <span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> e<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">5000</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>没错，使用Lambda表达式，又是一行代码就搞定了！！</p> <p>运行test9方法，输出如下的结果信息。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>张三, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">18</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">9999.99</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>李四, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">38</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">5555.55</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>王五, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">60</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">6666.66</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>赵六, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">16</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">7777.77</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>另外，使用Lambda表达式时，只需要给出需要过滤的集合，我们就能够实现从集合中过滤指定规则的元素，并输出结果信息。</p> <p><strong>5.重头戏：Stream API</strong></p> <p>使用Lambda表达式结合Stream API，只要给出相应的集合，我们就可以完成对集合的各种过滤并输出结果信息。</p> <p>例如，此时只要有一个<code>employees</code>集合，我们使用Lambda表达式来获取工资大于或者等于5000的员工信息。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test10</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> e<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">5000</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>没错，<strong>只给出一个集合，使用Lambda表达式和Stream API，一行代码就能够过滤出想要的元素并进行输出。</strong></p> <p>运行test10方法，输出如下的结果信息。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>张三, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">18</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">9999.99</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>李四, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">38</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">5555.55</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>王五, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">60</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">6666.66</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>赵六, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">16</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">7777.77</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>如果我们只想要获取前两个员工的信息呢？其实也很简单，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test11</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> e<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">5000</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">limit</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>可以看到，我们在代码中添加了<code>limit(2)</code>来限制只获取两个员工信息。运行test11方法，输出如下的结果信息。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>张三, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">18</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">9999.99</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>李四, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">38</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">5555.55</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>使用Lambda表达式和Stream API也可以获取指定的字段信息，例如获取工资大于或者等于5000的员工姓名。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test12</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> e<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">5000</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">Employee</span><span class="token operator">::</span><span class="token function">getName</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>可以看到，使用map过滤出了工资大于或者等于5000的员工姓名。运行test12方法，输出如下的结果信息。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>张三
李四
王五
赵六
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>是不是很简单呢？</p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194346223.jpg#pic_center" loading="lazy" class="lazy"></p> <p>最后，给出文中使用的设计模式：<strong>策略模式。</strong></p> <h3 id="匿名类到lambda表达式"><a href="#匿名类到lambda表达式" class="header-anchor">#</a> 匿名类到Lambda表达式</h3> <p>我们先来看看从匿名类如何转换到Lambda表达式呢？</p> <p>这里，我们可以使用两个示例来说明如何从匿名内部类转换为Lambda表达式。</p> <ul><li>匿名内部类到Lambda表达式</li></ul> <p>使用匿名内部类如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Runnable</span> r <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;Hello Lambda&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>转化为Lambda表达式如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Runnable</span> r <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;Hello Lambda&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><ul><li>匿名内部类作为参数传递到Lambda表达式作为参数传递</li></ul> <p>使用匿名内部类作为参数如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">TreeSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> ts <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TreeSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">compare</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> o1<span class="token punctuation">,</span> <span class="token class-name">Integer</span> o2<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>o1<span class="token punctuation">,</span> o2<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>使用Lambda表达式作为参数如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">TreeSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> ts <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TreeSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span>
	<span class="token punctuation">(</span>o1<span class="token punctuation">,</span> o2<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>o1<span class="token punctuation">,</span> o2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>从直观上看，Lambda表达式要比常规的语法简洁的多。</p> <h3 id="lambda表达式的语法"><a href="#lambda表达式的语法" class="header-anchor">#</a> Lambda表达式的语法</h3> <p>Lambda表达式在Java语言中引入了 “-&gt;” 操作符， “-&gt;” 操作符被称为Lambda表达式的操作符或者箭头操作符，它将Lambda表达式分为两部分：</p> <ul><li><strong>左侧部分指定了Lambda表达式需要的所有参数。</strong></li></ul> <p>Lambda表达式本质上是对接口的实现，Lambda表达式的参数列表本质上对应着接口中方法的参数列表。</p> <ul><li><strong>右侧部分指定了Lambda体，即Lambda表达式要执行的功能。</strong></li></ul> <p>Lambda体本质上就是接口方法具体实现的功能。</p> <p>我们可以将Lambda表达式的语法总结如下。</p> <p><strong>1.语法格式一：无参，无返回值，Lambda体只有一条语句</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Runnable</span> r <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;Hello Lambda&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>具体示例如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">Runnable</span> r <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;Hello Lambda&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span>r<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p><strong>2.语法格式二：Lambda表达式需要一个参数，并且无返回值</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Consumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> func <span class="token operator">=</span> <span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>具体示例如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">Consumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> consumer <span class="token operator">=</span> <span class="token punctuation">(</span>x<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span><span class="token punctuation">;</span>
    consumer<span class="token punctuation">.</span><span class="token function">accept</span><span class="token punctuation">(</span><span class="token string">&quot;Hello Lambda&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p><strong>3.语法格式三：Lambda只需要一个参数时，参数的小括号可以省略</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Consumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> func <span class="token operator">=</span> s <span class="token operator">-&gt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>具体示例如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test3</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">Consumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> consumer <span class="token operator">=</span> x <span class="token operator">-&gt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span><span class="token punctuation">;</span>
    consumer<span class="token punctuation">.</span><span class="token function">accept</span><span class="token punctuation">(</span><span class="token string">&quot;Hello Lambda&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p><strong>4.语法格式四：Lambda需要两个参数，并且有返回值</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">BinaryOperator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> bo <span class="token operator">=</span> <span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;函数式接口&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> a <span class="token operator">+</span> b<span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>具体示例如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test4</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> comparator <span class="token operator">=</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;函数式接口&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p><strong>5.语法格式五：当Lambda体只有一条语句时，return和大括号可以省略</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">BinaryOperator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> bo <span class="token operator">=</span> <span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> a <span class="token operator">+</span> b<span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>具体示例如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test5</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> comparator <span class="token operator">=</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token operator">-&gt;</span>  <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p><strong>6.语法格式六：Lambda表达式的参数列表的数据类型可以省略不写，因为JVM编译器能够通过上下文推断出数据类型，这就是“类型推断”</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">BinaryOperator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> bo <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Integer</span> a<span class="token punctuation">,</span> <span class="token class-name">Integer</span> b<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> a <span class="token operator">+</span> b<span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>等同于</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">BinaryOperator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> bo <span class="token operator">=</span> <span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> a <span class="token operator">+</span> b<span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>上述 Lambda 表达式中的参数类型都是由编译器推断得出的。 Lambda 表达式中无需指定类型，程序依然可以编译，这是因为 javac 根据程序的上下文，在后台推断出了参数的类型。 Lambda 表达式的类型依赖于上下文环境，是由编译器推断出来的。这就是所谓的“类型推断”。</p> <h3 id="函数式接口"><a href="#函数式接口" class="header-anchor">#</a> 函数式接口</h3> <p>Lambda表达式需要函数式接口的支持，所以，我们有必要来说说什么是函数式接口。</p> <blockquote><p>只包含一个抽象方法的接口，称为函数式接口。</p> <p>可以通过 Lambda 表达式来创建该接口的对象。（若 Lambda表达式抛出一个受检异常，那么该异常需要在目标接口的抽象方法上进行声明）。</p> <p>可以在任意函数式接口上使用 @FunctionalInterface 注解，这样做可以检查它是否是一个函数式接口，同时 javadoc 也会包含一条声明，说明这个接口是一个函数式接口。</p></blockquote> <p>我们可以自定义函数式接口，并使用Lambda表达式来实现相应的功能。</p> <p>例如，使用函数式接口和Lambda表达式实现对字符串的处理功能。</p> <p>首先，我们定义一个函数式接口MyFunc，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@FunctionalInterface</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">MyFunc</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token class-name">T</span> <span class="token function">getValue</span><span class="token punctuation">(</span><span class="token class-name">T</span> t<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>接下来，我们定义一个操作字符串的方法，其中参数为MyFunc接口实例和需要转换的字符串。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">handlerString</span><span class="token punctuation">(</span><span class="token class-name">MyFunc</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> myFunc<span class="token punctuation">,</span> <span class="token class-name">String</span> str<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">return</span> myFunc<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>接下来，我们对自定义的函数式接口进行测试，此时我们传递的函数式接口的参数为Lambda表达式，并且将字符串转化为大写。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test6</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">String</span> str <span class="token operator">=</span> <span class="token function">handlerString</span><span class="token punctuation">(</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> s<span class="token punctuation">.</span><span class="token function">toUpperCase</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>运行test6方法，得出的结果信息如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>BINGHE
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们也可以截取字符串的某一部分，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test7</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">String</span> str <span class="token operator">=</span> <span class="token function">handlerString</span><span class="token punctuation">(</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> s<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>运行test7方法，得出的结果信息如下所示。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>bing
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>可以看到，我们可以通过<code>handlerString(MyFunc&lt;String&gt; myFunc, String str)</code>方法结合Lambda表达式对字符串进行任意操作。</p> <p><strong>注意：作为参数传递 Lambda 表达式：为了将 Lambda 表达式作为参数传递，接收Lambda 表达式的参数类型必须是与该 Lambda 表达式兼容的函数式接口的类型 。</strong></p> <h3 id="lambda表达式典型案例"><a href="#lambda表达式典型案例" class="header-anchor">#</a> Lambda表达式典型案例</h3> <h3 id="案例一"><a href="#案例一" class="header-anchor">#</a> 案例一</h3> <p><strong>需求</strong></p> <p>调用Collections.sort()方法，通过定制排序比较两个Employee（先比较年龄，年龄相同按姓名比较），使用Lambda表达式作为参数传递。</p> <p><strong>实现</strong></p> <p>这里，我们先创建一个Employee类，为了满足需求，我们在Employee类中定义了姓名、年龄和工资三个字段，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Data</span>
<span class="token annotation punctuation">@Builder</span>
<span class="token annotation punctuation">@ToString</span>
<span class="token annotation punctuation">@NoArgsConstructor</span>
<span class="token annotation punctuation">@AllArgsConstructor</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Employee</span> <span class="token keyword">implements</span> <span class="token class-name">Serializable</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">long</span> serialVersionUID <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">9079722457749166858L</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> name<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">Integer</span> age<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">Double</span> salary<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p>接下来，我们在TestLambda类中定义一个成员变量employees，employees变量是一个List集合，存储了Employee的一个列表，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">protected</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> employees <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;张三&quot;</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">,</span> <span class="token number">9999.99</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;李四&quot;</span><span class="token punctuation">,</span> <span class="token number">38</span><span class="token punctuation">,</span> <span class="token number">5555.55</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;王五&quot;</span><span class="token punctuation">,</span> <span class="token number">60</span><span class="token punctuation">,</span> <span class="token number">6666.66</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;赵六&quot;</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">7777.77</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;田七&quot;</span><span class="token punctuation">,</span> <span class="token number">58</span><span class="token punctuation">,</span> <span class="token number">3333.33</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>前期的准备工作完成了，接下来，我们就可以实现具体的业务逻辑了。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">Collections</span><span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span>employees<span class="token punctuation">,</span> <span class="token punctuation">(</span>e1<span class="token punctuation">,</span> e2<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>e1<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> e2<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            <span class="token keyword">return</span> e1<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">compareTo</span><span class="token punctuation">(</span>e2<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>e1<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e2<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p>上述代码比较简单，我就不赘述具体逻辑了。运行test1方法，得出的结果信息如下所示。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>赵六, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">8</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">7777.77</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>张三, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">18</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">9999.99</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>李四, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">38</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">5555.55</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>田七, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">58</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">3333.33</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>王五, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">60</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">6666.66</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>如果想倒叙输出如何处理呢，只需要在将<code>return Integer.compare(e1.getAge(), e2.getAge());</code>修改成<code>-return Integer.compare(e1.getAge(), e2.getAge());</code>即可，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">Collections</span><span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span>employees<span class="token punctuation">,</span> <span class="token punctuation">(</span>e1<span class="token punctuation">,</span> e2<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>e1<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> e2<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            <span class="token keyword">return</span> e1<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">compareTo</span><span class="token punctuation">(</span>e2<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> <span class="token operator">-</span><span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>e1<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e2<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p>再次运行test1方法，得出的结果信息如下所示。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>王五, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">60</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">6666.66</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>田七, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">58</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">3333.33</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>李四, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">38</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">5555.55</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>张三, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">18</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">9999.99</span><span class="token punctuation">)</span>
Employee<span class="token punctuation">(</span>name<span class="token operator">=</span>赵六, <span class="token assign-left variable">age</span><span class="token operator">=</span><span class="token number">8</span>, <span class="token assign-left variable">salary</span><span class="token operator">=</span><span class="token number">7777.77</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>结果符合我们的需求。</p> <h3 id="案例二"><a href="#案例二" class="header-anchor">#</a> 案例二</h3> <p><strong>需求</strong></p> <p>1.声明函数式接口，接口中声明抽象方法<code>public String getValue(String str);</code></p> <p>2.声明类TestLambda，类中编写方法使用接口作为参数，将一个字符串转换为大写，并作为方法的返回值。</p> <p>3.再将一个字符串的第2个和第4个索引位置进行截取子串。</p> <p><strong>实现</strong></p> <p>首先，创建一个函数式接口MyFunction，在MyFunction接口上加上注解@FunctionalInterface标识接口是一个函数式接口。如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@FunctionalInterface</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">MyFunction</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getValue</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>在TestLambda类中声明stringHandler方法，参数分别为待处理的字符串和函数式接口的实例，方法中的逻辑就是调用函数式接口的方法来处理字符串，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">stringHandler</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">,</span> <span class="token class-name">MyFunction</span> myFunction<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">return</span> myFunction<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>接下来，我们实现将一个字符串转换为大写的逻辑，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">String</span> value <span class="token operator">=</span> <span class="token function">stringHandler</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> <span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> s<span class="token punctuation">.</span><span class="token function">toUpperCase</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>运行test2方法，得出如下的结果信息。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>BINGHE
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们再来实现字符串截取的操作，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test3</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">String</span> value <span class="token operator">=</span> <span class="token function">stringHandler</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> <span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> s<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p><strong>注意：需求中是按照第2个和第4个索引位置进行截取子串，字符串的下标是从0开始的，所以这里截取字符串时使用的是substring(1, 3)，而不是substring(2, 4)，这也是很多小伙伴容易犯的错误。</strong></p> <p><strong>另外，使用上述Lambda表达式形式，可以实现字符串的任意处理，并返回处理后的新字符串。</strong></p> <p>运行test3方法，结果如下所示。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code><span class="token keyword">in</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><h3 id="案例三"><a href="#案例三" class="header-anchor">#</a> 案例三</h3> <p><strong>需求</strong></p> <p>1.声明一个带两个泛型的函数式接口，泛型类型为&lt;T, R&gt;，其中，T作为参数的类型，R作为返回值的类型。</p> <p>2.接口中声明对象的抽象方法。</p> <p>3.在TestLambda类中声明方法。使用接口作为参数计算两个long型参数的和。</p> <p>4.再就按两个long型参数的乘积。</p> <p><strong>实现</strong></p> <p>首先，我们按照需求定义函数式接口MyFunc，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@FunctionalInterface</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">MyFunc</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">,</span> <span class="token class-name">R</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>

    <span class="token class-name">R</span> <span class="token function">getValue</span><span class="token punctuation">(</span><span class="token class-name">T</span> t1<span class="token punctuation">,</span> <span class="token class-name">T</span> t2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>接下来，我们在TestLambda类中创建一个处理两个long型数据的方法，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">operate</span><span class="token punctuation">(</span><span class="token class-name">Long</span> num1<span class="token punctuation">,</span> <span class="token class-name">Long</span> num2<span class="token punctuation">,</span> <span class="token class-name">MyFunc</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Long</span><span class="token punctuation">,</span> <span class="token class-name">Long</span><span class="token punctuation">&gt;</span></span> myFunc<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>myFunc<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span>num1<span class="token punctuation">,</span> num2<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>我们可以使用下面的方法来完成两个long型参数的和。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test4</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token function">operate</span><span class="token punctuation">(</span><span class="token number">100L</span><span class="token punctuation">,</span> <span class="token number">200L</span><span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> x <span class="token operator">+</span> y<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>运行test4方法，结果如下所示。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code><span class="token number">300</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>实现两个long型数据的乘积，也很简单。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test5</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token function">operate</span><span class="token punctuation">(</span><span class="token number">100L</span><span class="token punctuation">,</span> <span class="token number">200L</span><span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> x <span class="token operator">*</span> y<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>运行test5方法，结果如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token number">20000</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>看到这里，我相信很多小伙伴已经对Lambda表达式有了更深层次的理解。只要多多练习，就能够更好的掌握Lambda表达式的精髓。</p> <h2 id="函数式接口总览"><a href="#函数式接口总览" class="header-anchor">#</a> 函数式接口总览</h2> <p>这里，我使用表格的形式来简单说明下Java8中提供的函数式接口。</p> <h3 id="四大核心函数式接口总览"><a href="#四大核心函数式接口总览" class="header-anchor">#</a> 四大核心函数式接口总览</h3> <p>首先，我们来看四大核心函数式接口，如下所示。</p> <table><thead><tr><th>函数式接口</th> <th>参数类型</th> <th style="text-align:left;">返回类型</th> <th>使用场景</th></tr></thead> <tbody><tr><td>Consumer<T>消费型接口</T></td> <td>T</td> <td style="text-align:left;">void</td> <td>对类型为T的对象应用操作，接口定义的方法：void accept(T t)</td></tr> <tr><td>Supplier<T>供给型接口</T></td> <td>无</td> <td style="text-align:left;">T</td> <td>返回类型为T的对象，接口定义的方法：T get()</td></tr> <tr><td>Function&lt;T, R&gt;函数式接口</td> <td>T</td> <td style="text-align:left;">R</td> <td>对类型为T的对象应用操作，并R类型的返回结果。接口定义的方法：R apply(T t)</td></tr> <tr><td>Predicate<T>断言型接口</T></td> <td>T</td> <td style="text-align:left;">boolean</td> <td>确定类型为T的对象是否满足约束条件，并返回boolean类型的数据。接口定义的方法：boolean test(T t)</td></tr></tbody></table> <h3 id="其他函数接口总览"><a href="#其他函数接口总览" class="header-anchor">#</a> 其他函数接口总览</h3> <p>除了四大核心函数接口外，Java8还提供了一些其他的函数式接口。</p> <table><thead><tr><th>函数式接口</th> <th>参数类型</th> <th>返回类型</th> <th>使用场景</th></tr></thead> <tbody><tr><td>BiFunction(T, U, R)</td> <td>T, U</td> <td>R</td> <td>对类型为T,U的参数应用操作，返回R类型的结果。接口定义的方法：R apply(T t, U u)</td></tr> <tr><td>UnaryOperator<T>（Function子接口）</T></td> <td>T</td> <td>T</td> <td>对类型为T的对象进行一 元运算， 并返回T类型的 结果。 包含方法为 T apply(T t)</td></tr> <tr><td>BinaryOperator<T> (BiFunction 子接口)</T></td> <td>T, T</td> <td>T</td> <td>对类型为T的对象进行二 元运算， 并返回T类型的 结果。 包含方法为 T apply(T t1, T t2)</td></tr> <tr><td>BiConsumer&lt;T, U&gt;</td> <td>T, U</td> <td>void</td> <td>对类型为T, U 参数应用 操作。 包含方法为 void accept(T t, U u)</td></tr> <tr><td>ToIntFunction<T></T></td> <td>T</td> <td>int</td> <td>计算int值的函数</td></tr> <tr><td>ToLongFunction<T></T></td> <td>T</td> <td>long</td> <td>计算long值的函数</td></tr> <tr><td>ToDoubleFunction<T></T></td> <td>T</td> <td>double</td> <td>计算double值的函数</td></tr> <tr><td>IntFunction<R></R></td> <td>int</td> <td>R</td> <td>参数为int 类型的函数</td></tr> <tr><td>LongFunction<R></R></td> <td>long</td> <td>R</td> <td>参数为 long类型的函数</td></tr> <tr><td>DoubleFunction<R></R></td> <td>double</td> <td>R</td> <td>参数为double类型的函数</td></tr></tbody></table> <h3 id="四大核心函数式接口"><a href="#四大核心函数式接口" class="header-anchor">#</a> 四大核心函数式接口</h3> <h3 id="consumer接口"><a href="#consumer接口" class="header-anchor">#</a> Consumer接口</h3> <p><strong>1.接口说明</strong></p> <p>Consumer接口是消费性接口，无返回值。Java8中对Consumer的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@FunctionalInterface</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">Consumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>

    <span class="token keyword">void</span> <span class="token function">accept</span><span class="token punctuation">(</span><span class="token class-name">T</span> t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">default</span> <span class="token class-name">Consumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">andThen</span><span class="token punctuation">(</span><span class="token class-name">Consumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> after<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">Objects</span><span class="token punctuation">.</span><span class="token function">requireNonNull</span><span class="token punctuation">(</span>after<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token class-name">T</span> t<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span> <span class="token function">accept</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span> after<span class="token punctuation">.</span><span class="token function">accept</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p><strong>2.使用示例</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">handlerConsumer</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> number<span class="token punctuation">,</span> <span class="token class-name">Consumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> consumer<span class="token punctuation">)</span><span class="token punctuation">{</span>
    consumer<span class="token punctuation">.</span><span class="token function">accept</span><span class="token punctuation">(</span>number<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">handlerConsumer</span><span class="token punctuation">(</span><span class="token number">10000</span><span class="token punctuation">,</span> <span class="token punctuation">(</span>i<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><h3 id="supplier接口"><a href="#supplier接口" class="header-anchor">#</a> Supplier接口</h3> <p><strong>1.接口说明</strong></p> <p>Supplier接口是供给型接口，有返回值，Java8中对Supplier接口的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@FunctionalInterface</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">Supplier</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>
    <span class="token class-name">T</span> <span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p><strong>2.使用示例</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> <span class="token function">getNumberList</span><span class="token punctuation">(</span><span class="token keyword">int</span> num<span class="token punctuation">,</span> <span class="token class-name">Supplier</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> supplier<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> list <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span><span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> num<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        list<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>supplier<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> list<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> numberList <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getNumberList</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token keyword">new</span> <span class="token class-name">Random</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">nextInt</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    numberList<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br></div></div><h3 id="function接口"><a href="#function接口" class="header-anchor">#</a> Function接口</h3> <p><strong>1.接口说明</strong></p> <p>Function接口是函数型接口，有返回值，Java8中对Function接口的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@FunctionalInterface</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">Function</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">,</span> <span class="token class-name">R</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>
    
    <span class="token class-name">R</span> <span class="token function">apply</span><span class="token punctuation">(</span><span class="token class-name">T</span> t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">default</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">V</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Function</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">V</span><span class="token punctuation">,</span> <span class="token class-name">R</span><span class="token punctuation">&gt;</span></span> <span class="token function">compose</span><span class="token punctuation">(</span><span class="token class-name">Function</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">V</span><span class="token punctuation">,</span> <span class="token operator">?</span> <span class="token keyword">extends</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> before<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">Objects</span><span class="token punctuation">.</span><span class="token function">requireNonNull</span><span class="token punctuation">(</span>before<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token class-name">V</span> v<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token function">apply</span><span class="token punctuation">(</span>before<span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span>v<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">default</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">V</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Function</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">,</span> <span class="token class-name">V</span><span class="token punctuation">&gt;</span></span> <span class="token function">andThen</span><span class="token punctuation">(</span><span class="token class-name">Function</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">R</span><span class="token punctuation">,</span> <span class="token operator">?</span> <span class="token keyword">extends</span> <span class="token class-name">V</span><span class="token punctuation">&gt;</span></span> after<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">Objects</span><span class="token punctuation">.</span><span class="token function">requireNonNull</span><span class="token punctuation">(</span>after<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token class-name">T</span> t<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> after<span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span><span class="token function">apply</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">static</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Function</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">,</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">identity</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> t <span class="token operator">-&gt;</span> t<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br></div></div><p><strong>2.使用示例</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">handlerString</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">,</span> <span class="token class-name">Function</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> func<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">return</span> func<span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test3</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">String</span> str <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">handlerString</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> <span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> s<span class="token punctuation">.</span><span class="token function">toUpperCase</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><h3 id="predicate接口"><a href="#predicate接口" class="header-anchor">#</a> Predicate接口</h3> <p><strong>1.接口说明</strong></p> <p>Predicate接口是断言型接口，返回值类型为boolean，Java8中对Predicate接口的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@FunctionalInterface</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>

    <span class="token keyword">boolean</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token class-name">T</span> t<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">default</span> <span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">and</span><span class="token punctuation">(</span><span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> other<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">Objects</span><span class="token punctuation">.</span><span class="token function">requireNonNull</span><span class="token punctuation">(</span>other<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span>t<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token function">test</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> other<span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">default</span> <span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">negate</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span>t<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token operator">!</span><span class="token function">test</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">default</span> <span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">or</span><span class="token punctuation">(</span><span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> other<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">Objects</span><span class="token punctuation">.</span><span class="token function">requireNonNull</span><span class="token punctuation">(</span>other<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span>t<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token function">test</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span> <span class="token operator">||</span> other<span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">static</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">isEqual</span><span class="token punctuation">(</span><span class="token class-name">Object</span> targetRef<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> targetRef<span class="token punctuation">)</span>
                <span class="token operator">?</span> <span class="token class-name">Objects</span><span class="token operator">::</span><span class="token function">isNull</span>
                <span class="token operator">:</span> object <span class="token operator">-&gt;</span> targetRef<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>object<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br></div></div><p><strong>2.使用示例</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> <span class="token function">filterString</span><span class="token punctuation">(</span><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> list<span class="token punctuation">,</span> <span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> predicate<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> strList <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span><span class="token punctuation">(</span><span class="token class-name">String</span> str <span class="token operator">:</span> list<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>predicate<span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            strList<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> strList<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test4</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> list <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token string">&quot;Hello&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;Lambda&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;lyz&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;World&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> strList <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">filterString</span><span class="token punctuation">(</span>list<span class="token punctuation">,</span> <span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> s<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    strList<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br></div></div><p><strong>注意：只要我们学会了Java8中四大核心函数式接口的用法，其他函数式接口我们也就知道如何使用了！</strong></p> <h2 id="java7与java8中的hashmap"><a href="#java7与java8中的hashmap" class="header-anchor">#</a> Java7与Java8中的HashMap</h2> <ul><li>JDK7 HashMap结构为数组+链表（发生元素碰撞时，会将新元素添加到链表开头）</li> <li>JDK8 HashMap结构为数组+链表+红黑树（发生元素碰撞时，会将新元素添加到链表末尾，当HashMap总容量大于等于64，并且某个链表的大小大于等于8，会将链表转化为红黑树（注意：红黑树是二叉树的一种））</li></ul> <h3 id="jdk8-hashmap重排序"><a href="#jdk8-hashmap重排序" class="header-anchor">#</a> JDK8 HashMap重排序</h3> <p>如果删除了HashMap中红黑树的某个元素导致元素重排序时，不需要计算待重排序的元素的HashCode码，只需要将当前元素放到（HashMap总长度+当前元素在HashMap中的位置）的位置即可。</p> <h2 id="筛选与切片"><a href="#筛选与切片" class="header-anchor">#</a> 筛选与切片</h2> <ul><li>filter——接收 Lambda ， 从流中排除某些元素。</li> <li>limit——截断流，使其元素不超过给定数量。</li> <li>skip(n) —— 跳过元素，返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个，则返回一个空流。与 limit(n) 互补</li> <li>distinct——筛选，通过流所生成元素的 hashCode() 和 equals() 去除重复元素</li></ul> <h2 id="中间操作"><a href="#中间操作" class="header-anchor">#</a> 中间操作</h2> <ul><li>map——接收 Lambda ， 将元素转换成其他形式或提取信息。接收一个函数作为参数，该函数会被应用到每个元素上，并将其映射成一个新的元素。</li> <li>flatMap——接收一个函数作为参数，将流中的每个值都换成另一个流，然后把所有流连接成一个流</li> <li>sorted()——自然排序</li> <li>sorted(Comparator com)——定制排序</li></ul> <h2 id="终止操作"><a href="#终止操作" class="header-anchor">#</a> 终止操作</h2> <ul><li>allMatch——检查是否匹配所有元素</li> <li>anyMatch——检查是否至少匹配一个元素</li> <li>noneMatch——检查是否没有匹配的元素</li> <li>findFirst——返回第一个元素</li> <li>findAny——返回当前流中的任意元素</li> <li>count——返回流中元素的总个数</li> <li>max——返回流中最大值</li> <li>min——返回流中最小值</li></ul> <h2 id="归约"><a href="#归约" class="header-anchor">#</a> 归约</h2> <ul><li>reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来，得到一个值。</li> <li>collect——将流转换为其他形式。接收一个 Collector接口的实现，用于给Stream中元素做汇总的方法</li></ul> <p><strong>注意：流进行了终止操作后，不能再次使用</strong></p> <h2 id="optional-容器类"><a href="#optional-容器类" class="header-anchor">#</a> Optional 容器类</h2> <p>用于尽量避免空指针异常</p> <ul><li>Optional.of(T t) : 创建一个 Optional 实例</li> <li>Optional.empty() : 创建一个空的 Optional 实例</li> <li>Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例</li> <li>isPresent() : 判断是否包含值</li> <li>orElse(T t) :  如果调用对象包含值，返回该值，否则返回t</li> <li>orElseGet(Supplier s) :如果调用对象包含值，返回该值，否则返回 s 获取的值</li> <li>map(Function f): 如果有值对其处理，并返回处理后的Optional，否则返回 Optional.empty()</li> <li>flatMap(Function mapper):与 map 类似，要求返回值必须是Optional</li></ul> <h2 id="方法引用与构造器引用"><a href="#方法引用与构造器引用" class="header-anchor">#</a> 方法引用与构造器引用</h2> <h3 id="方法引用"><a href="#方法引用" class="header-anchor">#</a> 方法引用</h3> <p>当要传递给Lambda体的操作，已经有实现的方法了，可以使用方法引用！这里需要注意的是：实现抽象方法的参数列表，必须与方法引用方法的参数列表保持一致！</p> <p>那么什么是方法引用呢？方法引用就是操作符“::”将方法名和对象或类的名字分隔开来。</p> <p>有如下三种使用情况：</p> <ul><li><p>对象::实例方法</p></li> <li><p>类::静态方法</p></li> <li><p>类::实例方法</p></li></ul> <p>这里，我们可以列举几个示例。</p> <p>例如：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token punctuation">(</span>x<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>等同于：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>例如：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">BinaryOperator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Double</span><span class="token punctuation">&gt;</span></span> bo <span class="token operator">=</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">pow</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>等同于</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">BinaryOperator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Double</span><span class="token punctuation">&gt;</span></span> bo <span class="token operator">=</span> <span class="token class-name">Math</span><span class="token operator">::</span><span class="token function">pow</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>例如：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token function">compare</span><span class="token punctuation">(</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> x<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>y<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>等同于</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token function">compare</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token operator">::</span><span class="token function">equals</span><span class="token punctuation">,</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>注意： 当需要引用方法的第一个参数是调用对象，并且第二个参数是需要引用方法的第二个参数(或无参数)时： ClassName::methodName 。</strong></p> <h3 id="构造器引用"><a href="#构造器引用" class="header-anchor">#</a> 构造器引用</h3> <p>格式如下所示：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">ClassName</span><span class="token operator">::</span><span class="token keyword">new</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>与函数式接口相结合，自动与函数式接口中方法兼容。可以把构造器引用赋值给定义的方法，与构造器参数列表要与接口中抽象方法的参数列表一致！</p> <p>例如：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Function</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">,</span> <span class="token class-name">MyClass</span><span class="token punctuation">&gt;</span></span> fun <span class="token operator">=</span> <span class="token punctuation">(</span>n<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token keyword">new</span> <span class="token class-name">MyClass</span><span class="token punctuation">(</span>n<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>等同于</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Function</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">,</span> <span class="token class-name">MyClass</span><span class="token punctuation">&gt;</span></span> fun <span class="token operator">=</span> <span class="token class-name">MyClass</span><span class="token operator">::</span><span class="token keyword">new</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><h3 id="数组引用"><a href="#数组引用" class="header-anchor">#</a> 数组引用</h3> <p>格式如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>type<span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">::</span><span class="token keyword">new</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>例如：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Function</span><span class="token operator">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">,</span> <span class="token class-name">Integer</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">&gt;</span> fun <span class="token operator">=</span> <span class="token punctuation">(</span>n<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token keyword">new</span> <span class="token class-name">Integer</span><span class="token punctuation">[</span>n<span class="token punctuation">]</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>等同于</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Function</span><span class="token operator">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">,</span> <span class="token class-name">Integer</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">&gt;</span> fun <span class="token operator">=</span> <span class="token class-name">Integer</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">::</span><span class="token keyword">new</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><h2 id="java8中的stream"><a href="#java8中的stream" class="header-anchor">#</a> Java8中的Stream</h2> <h3 id="什么是stream"><a href="#什么是stream" class="header-anchor">#</a> 什么是Stream?</h3> <p>Java8中有两大最为重要的改变。第一个是 Lambda 表达式；另外一个则是 Stream API(java.util.stream.*)。</p> <p>Stream 是 Java8 中处理集合的关键抽象概念，它可以指定你希望对集合进行的操作，可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作，就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之，Stream API 提供了一种高效且易于使用的处理数据的方式</p> <blockquote><p>流是数据渠道，用于操作数据源（集合、数组等）所生成的元素序列。“集合讲的是数据，流讲的是计算！ ”</p></blockquote> <p><strong>注意：</strong>
① Stream 自己不会存储元素。
② Stream 不会改变源对象。相反，他们会返回一个持有结果的新Stream。
③ Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。</p> <h3 id="stream操作的三个步骤"><a href="#stream操作的三个步骤" class="header-anchor">#</a> Stream操作的三个步骤</h3> <ul><li>创建 Stream</li></ul> <p>一个数据源（如： 集合、数组）， 获取一个流。</p> <ul><li>中间操作</li></ul> <p>一个中间操作链，对数据源的数据进行处理。</p> <ul><li>终止操作(终端操作)</li></ul> <p>一个终止操作，执行中间操作链，并产生结果 。</p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194548322.jpg" loading="lazy" class="lazy"></p> <h3 id="如何创建stream"><a href="#如何创建stream" class="header-anchor">#</a> 如何创建Stream?</h3> <p>Java8 中的 Collection 接口被扩展，提供了两个获取流的方法：</p> <p><strong>1.获取Stream</strong></p> <ul><li><p>default Stream<E> stream() : 返回一个顺序流</E></p></li> <li><p>default Stream<E> parallelStream() : 返回一个并行流</E></p></li></ul> <p><strong>2.由数组创建Stream</strong></p> <p>Java8 中的 Arrays 的静态方法 stream() 可以获取数组流：</p> <ul><li>static <T> Stream<T> stream(T[] array): 返回一个流</T></T></li></ul> <p>重载形式，能够处理对应基本类型的数组：</p> <ul><li><p>public static IntStream stream(int[] array)</p></li> <li><p>public static LongStream stream(long[] array)</p></li> <li><p>public static DoubleStream stream(double[] array)</p></li></ul> <p><strong>3.由值创建流</strong></p> <p>可以使用静态方法 Stream.of(), 通过显示值创建一个流。它可以接收任意数量的参数。</p> <ul><li>public static<T> Stream<T> of(T... values) : 返回一个流</T></T></li></ul> <p><strong>4.由函数创建流</strong></p> <p>由函数创建流可以创建无限流。</p> <p>可以使用静态方法 Stream.iterate() 和Stream.generate(), 创建无限流 。</p> <ul><li>迭代</li></ul> <p>public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)</T></T></T></p> <ul><li>生成</li></ul> <p>public static<T> Stream<T> generate(Supplier<T> s)</T></T></T></p> <h3 id="stream的中间操作"><a href="#stream的中间操作" class="header-anchor">#</a> Stream的中间操作</h3> <p>多个中间操作可以连接起来形成一个流水线，除非流水线上触发终止操作，否则中间操作不会执行任何的处理！而在终止操作时一次性全部处理，称为“惰性求值”</p> <p><strong>1.筛选与切片</strong></p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194603610.jpg" loading="lazy" class="lazy"></p> <p><strong>2.映射</strong></p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194613380.jpg" loading="lazy" class="lazy"></p> <p><strong>3.排序</strong></p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194740329.jpg" loading="lazy" class="lazy"></p> <h3 id="stream-的终止操作"><a href="#stream-的终止操作" class="header-anchor">#</a> Stream 的终止操作</h3> <p>终端操作会从流的流水线生成结果。其结果可以是任何不是流的值，例如： List、 Integer，甚至是 void 。</p> <p><strong>1.查找与匹配</strong></p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194920966.jpg" loading="lazy" class="lazy"></p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314194943389.jpg" loading="lazy" class="lazy"></p> <p><strong>2.规约</strong></p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/2021031419495658.jpg#pic_center" loading="lazy" class="lazy"></p> <p><strong>3.收集</strong></p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314195011212.jpg#pic_center" loading="lazy" class="lazy"></p> <p>Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、 Set、 Map)。但是 Collectors 实用类提供了很多静态方法，可以方便地创建常见收集器实例， 具体方法与实例如下表</p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314195051385.jpg" loading="lazy" class="lazy"></p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314195103476.jpg" loading="lazy" class="lazy"></p> <h3 id="并行流与串行流"><a href="#并行流与串行流" class="header-anchor">#</a> 并行流与串行流</h3> <p>并行流就是把一个内容分成多个数据块，并用不同的线程分别处理每个数据块的流。</p> <p>Java 8 中将并行进行了优化，我们可以很容易的对数据进行并行操作。 Stream API 可以声明性地通过 parallel() 与
sequential() 在并行流与顺序流之间进行切换</p> <h3 id="fork-join-框架"><a href="#fork-join-框架" class="header-anchor">#</a> Fork/Join 框架</h3> <p><strong>1.简单概述</strong></p> <p>Fork/Join 框架： 就是在必要的情况下，将一个大任务，进行拆分(fork)成若干个小任务（拆到不可再拆时），再将一个个的小任务运算的结果进行 join 汇总.<br> <img alt="" data-src="https://img-blog.csdnimg.cn/2021031419511858.jpg" loading="lazy" class="lazy"></p> <p><strong>2.Fork/Join 框架与传统线程池的区别</strong></p> <p>采用 “工作窃取”模式（work-stealing）：
当执行新的任务时它可以将其拆分分成更小的任务执行，并将小任务加到线程队列中，然后再从一个随机线程的队列中偷一个并把它放在自己的队列中。</p> <p>相对于一般的线程池实现,fork/join框架的优势体现在对其中包含的任务的处理方式上.在一般的线程池中,如果一个线程正在执行的任务由于某些原因无法继续运行,那么该线程会处于等待状态.而在fork/join框架实现中,如果某个子问题由于等待另外一个子问题的完成而无法继续运行.那么处理该子问题的线程会主动寻找其他尚未运行的子问题来执行.这种方式减少了线程的等待时间,提高了性能。</p> <h3 id="stream概述"><a href="#stream概述" class="header-anchor">#</a> Stream概述</h3> <p>Java8中有两大最为重要的改变。第一个是 Lambda 表达式；另外一个则是 Stream API(java.util.stream.*)。</p> <p>Stream 是 Java8 中处理集合的关键抽象概念，它可以指定你希望对集合进行的操作，可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作，就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之，Stream API 提供了一种高效且易于使用的处理数据的方式。</p> <h3 id="何为stream"><a href="#何为stream" class="header-anchor">#</a> 何为Stream?</h3> <p><strong>流(Stream) 到底是什么呢？</strong></p> <blockquote><p>可以这么理解流：流就是数据渠道，用于操作数据源（集合、数组等）所生成的元素序列。</p></blockquote> <p>“集合讲的是数据，流讲的是计算！ ”</p> <p><strong>注意：</strong></p> <p>①Stream 自己不会存储元素。</p> <p>②Stream 不会改变源对象。相反，他们会返回一个持有结果的新Stream。</p> <p>③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。</p> <h3 id="stream操作步骤"><a href="#stream操作步骤" class="header-anchor">#</a> Stream操作步骤</h3> <p><strong>1.创建 Stream</strong></p> <p>一个数据源（如： 集合、数组）， 获取一个流。</p> <p><strong>2.中间操作</strong></p> <p>一个中间操作链，对数据源的数据进行处理。</p> <p><strong>3.终止操作(终端操作)</strong></p> <p>一个终止操作，执行中间操作链，并产生结果 。</p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/202103141952071.jpg" loading="lazy" class="lazy"></p> <h3 id="如何创建stream流"><a href="#如何创建stream流" class="header-anchor">#</a> 如何创建Stream流？</h3> <p>这里，创建测试类TestStreamAPI1，所有的操作都是在TestStreamAPI1类中完成的。</p> <p><strong>（1）通过Collection系列集合提供的stream()方法或者parallelStream()方法来创建Stream。</strong></p> <p>在Java8中，Collection 接口被扩展，提供了两个获取流的默认方法，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">default</span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">&gt;</span></span> <span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token class-name">StreamSupport</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token function">spliterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">default</span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">&gt;</span></span> <span class="token function">parallelStream</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token class-name">StreamSupport</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token function">spliterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>其中，stream()方法返回一个顺序流，parallelStream()方法返回一个并行流。</p> <p>我们可以使用如下代码方式来创建顺序流和并行流。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> list <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
list<span class="token punctuation">.</span><span class="token function">parallelStream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p><strong>（2）通过Arrays中的静态方法stream()获取数组流。</strong></p> <p>Java8 中的 Arrays类的静态方法 stream() 可以获取数组流 ，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">stream</span><span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">[</span><span class="token punctuation">]</span> array<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">stream</span><span class="token punctuation">(</span>array<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> array<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>上述代码的的作用为：传入一个泛型数组，返回这个泛型的Stream流。</p> <p>除此之外，在Arrays类中还提供了stream()方法的如下重载形式。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">stream</span><span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">[</span><span class="token punctuation">]</span> array<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">stream</span><span class="token punctuation">(</span>array<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> array<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">stream</span><span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">[</span><span class="token punctuation">]</span> array<span class="token punctuation">,</span> <span class="token keyword">int</span> startInclusive<span class="token punctuation">,</span> <span class="token keyword">int</span> endExclusive<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token class-name">StreamSupport</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token function">spliterator</span><span class="token punctuation">(</span>array<span class="token punctuation">,</span> startInclusive<span class="token punctuation">,</span> endExclusive<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">IntStream</span> <span class="token function">stream</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> array<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">stream</span><span class="token punctuation">(</span>array<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> array<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">IntStream</span> <span class="token function">stream</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> array<span class="token punctuation">,</span> <span class="token keyword">int</span> startInclusive<span class="token punctuation">,</span> <span class="token keyword">int</span> endExclusive<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token class-name">StreamSupport</span><span class="token punctuation">.</span><span class="token function">intStream</span><span class="token punctuation">(</span><span class="token function">spliterator</span><span class="token punctuation">(</span>array<span class="token punctuation">,</span> startInclusive<span class="token punctuation">,</span> endExclusive<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">LongStream</span> <span class="token function">stream</span><span class="token punctuation">(</span><span class="token keyword">long</span><span class="token punctuation">[</span><span class="token punctuation">]</span> array<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">stream</span><span class="token punctuation">(</span>array<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> array<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">LongStream</span> <span class="token function">stream</span><span class="token punctuation">(</span><span class="token keyword">long</span><span class="token punctuation">[</span><span class="token punctuation">]</span> array<span class="token punctuation">,</span> <span class="token keyword">int</span> startInclusive<span class="token punctuation">,</span> <span class="token keyword">int</span> endExclusive<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token class-name">StreamSupport</span><span class="token punctuation">.</span><span class="token function">longStream</span><span class="token punctuation">(</span><span class="token function">spliterator</span><span class="token punctuation">(</span>array<span class="token punctuation">,</span> startInclusive<span class="token punctuation">,</span> endExclusive<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">DoubleStream</span> <span class="token function">stream</span><span class="token punctuation">(</span><span class="token keyword">double</span><span class="token punctuation">[</span><span class="token punctuation">]</span> array<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">stream</span><span class="token punctuation">(</span>array<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> array<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">DoubleStream</span> <span class="token function">stream</span><span class="token punctuation">(</span><span class="token keyword">double</span><span class="token punctuation">[</span><span class="token punctuation">]</span> array<span class="token punctuation">,</span> <span class="token keyword">int</span> startInclusive<span class="token punctuation">,</span> <span class="token keyword">int</span> endExclusive<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token class-name">StreamSupport</span><span class="token punctuation">.</span><span class="token function">doubleStream</span><span class="token punctuation">(</span><span class="token function">spliterator</span><span class="token punctuation">(</span>array<span class="token punctuation">,</span> startInclusive<span class="token punctuation">,</span> endExclusive<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br></div></div><p>基本上能够满足基本将基本类型的数组转化为Stream流的操作。</p> <p>我们可以通过下面的代码示例来使用Arrays类的stream()方法来创建Stream流。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Integer</span><span class="token punctuation">[</span><span class="token punctuation">]</span> nums <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Integer</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token number">6</span><span class="token punctuation">,</span><span class="token number">7</span><span class="token punctuation">,</span><span class="token number">8</span><span class="token punctuation">,</span><span class="token number">9</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> numStream <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span>nums<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>（3）通过Stream类的静态方法of()获取数组流。</strong></p> <p>可以使用静态方法 Stream.of(), 通过显示值创建一个流。它可以接收任意数量的参数。</p> <p>我们先来看看Stream的of()方法，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">static</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">of</span><span class="token punctuation">(</span><span class="token class-name">T</span> t<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token class-name">StreamSupport</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Streams<span class="token punctuation">.</span>StreamBuilderImpl</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token annotation punctuation">@SafeVarargs</span>
<span class="token annotation punctuation">@SuppressWarnings</span><span class="token punctuation">(</span><span class="token string">&quot;varargs&quot;</span><span class="token punctuation">)</span> 
<span class="token keyword">public</span> <span class="token keyword">static</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">of</span><span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> values<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span>values<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>可以看到，在Stream类中，提供了两个of()方法，一个只需要传入一个泛型参数，一个需要传入一个可变泛型参数。</p> <p>我们可以使用下面的代码示例来使用of方法创建一个Stream流。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> strStream <span class="token operator">=</span> <span class="token class-name">Stream</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token string">&quot;a&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;b&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;c&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>（4）创建无限流</strong></p> <p>可以使用静态方法 Stream.iterate() 和Stream.generate(), 创建无限流。</p> <p>先来看看Stream类中iterate()方法和generate()方法的源码，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">static</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">iterate</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token class-name">T</span> seed<span class="token punctuation">,</span> <span class="token keyword">final</span> <span class="token class-name">UnaryOperator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> f<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token class-name">Objects</span><span class="token punctuation">.</span><span class="token function">requireNonNull</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">final</span> <span class="token class-name">Iterator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> iterator <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Iterator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token annotation punctuation">@SuppressWarnings</span><span class="token punctuation">(</span><span class="token string">&quot;unchecked&quot;</span><span class="token punctuation">)</span>
        <span class="token class-name">T</span> t <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">)</span> <span class="token class-name">Streams</span><span class="token punctuation">.</span>NONE<span class="token punctuation">;</span>

        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">hasNext</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> <span class="token class-name">T</span> <span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> t <span class="token operator">=</span> <span class="token punctuation">(</span>t <span class="token operator">==</span> <span class="token class-name">Streams</span><span class="token punctuation">.</span>NONE<span class="token punctuation">)</span> <span class="token operator">?</span> seed <span class="token operator">:</span> f<span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token class-name">StreamSupport</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token class-name">Spliterators</span><span class="token punctuation">.</span><span class="token function">spliteratorUnknownSize</span><span class="token punctuation">(</span>
        iterator<span class="token punctuation">,</span>
        <span class="token class-name">Spliterator</span><span class="token punctuation">.</span>ORDERED <span class="token operator">|</span> <span class="token class-name">Spliterator</span><span class="token punctuation">.</span>IMMUTABLE<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">static</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">generate</span><span class="token punctuation">(</span><span class="token class-name">Supplier</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> s<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token class-name">Objects</span><span class="token punctuation">.</span><span class="token function">requireNonNull</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token class-name">StreamSupport</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span>
        <span class="token keyword">new</span> <span class="token class-name">StreamSpliterators<span class="token punctuation">.</span>InfiniteSupplyingSpliterator<span class="token punctuation">.</span>OfRef</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token class-name">Long</span><span class="token punctuation">.</span>MAX_VALUE<span class="token punctuation">,</span> s<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br></div></div><p>通过源码可以看出，iterate()方法主要是使用“迭代”的方式生成无限流，而generate()方法主要是使用“生成”的方式生成无限流。我们可以使用下面的代码示例来使用这两个方法生成Stream流。</p> <ul><li>迭代</li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> intStream <span class="token operator">=</span> <span class="token class-name">Stream</span><span class="token punctuation">.</span><span class="token function">iterate</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> x <span class="token operator">+</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
intStream<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>运行上述代码，会在终端一直输出偶数，这种操作会一直持续下去。如果我们只需要输出10个偶数，该如何操作呢？其实也很简单，使用Stream对象的limit方法进行限制就可以了，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> intStream <span class="token operator">=</span> <span class="token class-name">Stream</span><span class="token punctuation">.</span><span class="token function">iterate</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> x <span class="token operator">+</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
intStream<span class="token punctuation">.</span><span class="token function">limit</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><ul><li>生成</li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Stream</span><span class="token punctuation">.</span><span class="token function">generate</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">random</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>上述代码同样会一直输出随机数，如果我们只需要输出5个随机数，则只需要使用limit()方法进行限制即可。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Stream</span><span class="token punctuation">.</span><span class="token function">generate</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">random</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">limit</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>（5）创建空流</strong></p> <p>在Stream类中提供了一个empty()方法，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">static</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">empty</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token class-name">StreamSupport</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token class-name">Spliterators</span><span class="token punctuation">.</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span><span class="token function">emptySpliterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>我们可以使用Stream类的empty()方法来创建一个空Stream流，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> empty <span class="token operator">=</span> <span class="token class-name">Stream</span><span class="token punctuation">.</span><span class="token function">empty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><h3 id="stream的中间操作-2"><a href="#stream的中间操作-2" class="header-anchor">#</a> Stream的中间操作</h3> <p>多个中间操作可以连接起来形成一个流水线，除非流水线上触发终止操作，否则中间操作不会执行任何的处理！而在终止操作时一次性全部处理，称为“惰性求值” 。  Stream的中间操作是不会有任何结果数据输出的。</p> <p>Stream的中间操作在整体上可以分为：筛选与切片、映射、排序。接下来，我们就分别对这些中间操作进行简要的说明。</p> <h3 id="筛选与切片-2"><a href="#筛选与切片-2" class="header-anchor">#</a> 筛选与切片</h3> <p>这里，我将与筛选和切片有关的操作整理成如下表格。</p> <table><thead><tr><th>方法</th> <th>描述</th></tr></thead> <tbody><tr><td>filter(Predicate p)</td> <td>接收Lambda表达式，从流中排除某些元素</td></tr> <tr><td>distinct()</td> <td>筛选，通过流所生成元素的 hashCode() 和 equals() 去 除重复元素</td></tr> <tr><td>limit(long maxSize)</td> <td>截断流，使其元素不超过给定数量</td></tr> <tr><td>skip(long n)</td> <td>跳过元素，返回一个扔掉了前 n 个元素的流。若流中元素 不足 n 个，则返回一个空流。与 limit(n) 互补</td></tr></tbody></table> <p>接下来，我们列举几个简单的示例，以便加深理解。</p> <p>为了更好的测试程序，我先构造了一个对象数组，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">protected</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> list <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;张三&quot;</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">,</span> <span class="token number">9999.99</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;李四&quot;</span><span class="token punctuation">,</span> <span class="token number">38</span><span class="token punctuation">,</span> <span class="token number">5555.55</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;王五&quot;</span><span class="token punctuation">,</span> <span class="token number">60</span><span class="token punctuation">,</span> <span class="token number">6666.66</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;赵六&quot;</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">7777.77</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;田七&quot;</span><span class="token punctuation">,</span> <span class="token number">58</span><span class="token punctuation">,</span> <span class="token number">3333.33</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>其中，Employee类的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Data</span>
<span class="token annotation punctuation">@Builder</span>
<span class="token annotation punctuation">@ToString</span>
<span class="token annotation punctuation">@NoArgsConstructor</span>
<span class="token annotation punctuation">@AllArgsConstructor</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Employee</span> <span class="token keyword">implements</span> <span class="token class-name">Serializable</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">long</span> serialVersionUID <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">9079722457749166858L</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> name<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">Integer</span> age<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">Double</span> salary<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p>Employee类的定义比较简单，这里，我就不赘述了。之后的示例中，我们都是使用的Employee对象的集合进行操作。好了，我们开始具体的操作案例。</p> <p><strong>1.filter()方法</strong></p> <p>filter()方法主要是用于接收Lambda表达式，从流中排除某些元素，其在Stream接口中的源码如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">filter</span><span class="token punctuation">(</span><span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> predicate<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>可以看到，在filter()方法中，需要传递Predicate接口的对象，Predicate接口又是个什么鬼呢？点进去看下源码。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@FunctionalInterface</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>

    <span class="token keyword">boolean</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token class-name">T</span> t<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">default</span> <span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">and</span><span class="token punctuation">(</span><span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> other<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">Objects</span><span class="token punctuation">.</span><span class="token function">requireNonNull</span><span class="token punctuation">(</span>other<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span>t<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token function">test</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> other<span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">default</span> <span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">negate</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span>t<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token operator">!</span><span class="token function">test</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    
    <span class="token keyword">default</span> <span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">or</span><span class="token punctuation">(</span><span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> other<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">Objects</span><span class="token punctuation">.</span><span class="token function">requireNonNull</span><span class="token punctuation">(</span>other<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span>t<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token function">test</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span> <span class="token operator">||</span> other<span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    
    <span class="token keyword">static</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">isEqual</span><span class="token punctuation">(</span><span class="token class-name">Object</span> targetRef<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> targetRef<span class="token punctuation">)</span>
                <span class="token operator">?</span> <span class="token class-name">Objects</span><span class="token operator">::</span><span class="token function">isNull</span>
                <span class="token operator">:</span> object <span class="token operator">-&gt;</span> targetRef<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>object<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br></div></div><p>可以看到，Predicate是一个函数式接口，其中接口中定义的主要方法为test()方法，test()方法会接收一个泛型对象t，返回一个boolean类型的数据。</p> <p>看到这里，相信大家明白了：filter()方法是根据Predicate接口的test()方法的返回结果来过滤数据的，如果test()方法的返回结果为true，符合规则；如果test()方法的返回结果为false，则不符合规则。</p> <p>这里，我们可以使用下面的示例来简单的说明filter()方法的使用方式。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">//内部迭代：在此过程中没有进行过迭代，由Stream api进行迭代</span>
<span class="token comment">//中间操作：不会执行任何操作</span>
<span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Person</span><span class="token punctuation">&gt;</span></span> stream <span class="token operator">=</span> list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;Stream API 中间操作&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> e<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;</span> <span class="token number">30</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>我们，在执行终止语句之后，一边迭代，一边打印，而我们并没有去迭代上面集合，其实这是内部迭代，由Stream API 完成。</p> <p>下面我们来看看外部迭代，也就是我们人为得迭代。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">//外部迭代</span>
<span class="token class-name">Iterator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Person</span><span class="token punctuation">&gt;</span></span> it <span class="token operator">=</span> list<span class="token punctuation">.</span><span class="token function">iterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">while</span> <span class="token punctuation">(</span>it<span class="token punctuation">.</span><span class="token function">hasNext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>it<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p><strong>2.limit()方法</strong></p> <p>主要作用为：截断流，使其元素不超过给定数量。</p> <p>先来看limit方法的定义，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">limit</span><span class="token punctuation">(</span><span class="token keyword">long</span> maxSize<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>limit()方法在Stream接口中的定义比较简单，只需要传入一个long类型的数字即可。</p> <p>我们可以按照如下所示的代码来使用limit()方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">//过滤之后取2个值</span>
list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> e<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;</span><span class="token number">30</span> <span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">limit</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out <span class="token operator">::</span> <span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>在这里，我们可以配合其他得中间操作，并截断流，使我们可以取得相应个数得元素。而且在上面计算中，只要发现有2条符合条件得元素，则不会继续往下迭代数据，可以提高效率。</p> <p><strong>3.skip()方法</strong></p> <p>跳过元素，返回一个扔掉了前 n 个元素的流。若流中元素 不足 n 个，则返回一个空流。与 limit(n) 互补。</p> <p>源码定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">skip</span><span class="token punctuation">(</span><span class="token keyword">long</span> n<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>源码定义比较简单，同样只需要传入一个long类型的数字即可。其含义是跳过n个元素。</p> <p>简单示例如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">//跳过前2个值</span>
list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">skip</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out <span class="token operator">::</span> <span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>4.distinct()方法</strong></p> <p>筛选，通过流所生成元素的 hashCode() 和 equals() 去 除重复元素。</p> <p>源码定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">distinct</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>旨在对流中的元素进行去重。</p> <p>我们可以如下面的方式来使用disinct()方法。</p> <div class="language- line-numbers-mode"><pre class="language-text"><code>list.stream().distinct().forEach(System.out :: println);
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>这里有一个需要注意的地方：distinct 需要实体中重写hashCode（）和 equals（）方法才可以使用。</strong></p> <h3 id="映射"><a href="#映射" class="header-anchor">#</a> 映射</h3> <p>关于映射相关的方法如下表所示。</p> <table><thead><tr><th>方法</th> <th>描述</th></tr></thead> <tbody><tr><td>map(Function f)</td> <td>接收一个函数作为参数，该函数会被应用到每个元 素上，并将其映射成一个新的元素。</td></tr> <tr><td>mapToDouble(ToDoubleFunction f)</td> <td>接收一个函数作为参数，该函数会被应用到每个元 素上，产生一个新的 DoubleStream。</td></tr> <tr><td>mapToInt(ToIntFunction f)</td> <td>接收一个函数作为参数，该函数会被应用到每个元 素上，产生一个新的 IntStream。</td></tr> <tr><td>mapToLong(ToLongFunction f)</td> <td>接收一个函数作为参数，该函数会被应用到每个元 素上，产生一个新的 LongStream</td></tr> <tr><td>flatMap(Function f)</td> <td>接收一个函数作为参数，将流中的每个值都换成另 一个流，然后把所有流连接成一个流</td></tr></tbody></table> <p><strong>1.map()方法</strong></p> <p>接收一个函数作为参数，该函数会被应用到每个元 素上，并将其映射成一个新的元素。</p> <p>先来看Java8中Stream接口对于map()方法的声明，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">R</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">R</span><span class="token punctuation">&gt;</span></span> <span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">Function</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">,</span> <span class="token operator">?</span> <span class="token keyword">extends</span> <span class="token class-name">R</span><span class="token punctuation">&gt;</span></span> mapper<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们可以按照如下方式使用map()方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">//将流中每一个元素都映射到map的函数中，每个元素执行这个函数，再返回</span>
<span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> list <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token string">&quot;aaa&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;bbb&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;ccc&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;ddd&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> e<span class="token punctuation">.</span><span class="token function">toUpperCase</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">printf</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">//获取Person中的每一个人得名字name，再返回一个集合</span>
<span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> names <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">Person</span> <span class="token operator">::</span> <span class="token function">getName</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p><strong>2.flatMap()</strong></p> <p>接收一个函数作为参数，将流中的每个值都换成另 一个流，然后把所有流连接成一个流。</p> <p>先来看Java8中Stream接口对于flatMap()方法的声明，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">R</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">R</span><span class="token punctuation">&gt;</span></span> <span class="token function">flatMap</span><span class="token punctuation">(</span><span class="token class-name">Function</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">,</span> <span class="token operator">?</span> <span class="token keyword">extends</span> <span class="token class-name">Stream</span><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">extends</span> <span class="token class-name">R</span><span class="token punctuation">&gt;</span><span class="token punctuation">&gt;</span></span> mapper<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们可以使用如下方式使用flatMap()方法，为了便于大家理解，这里，我就贴出了测试flatMap()方法的所有代码。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">/**
     * flatMap —— 接收一个函数作为参数，将流中的每个值都换成一个流，然后把所有流连接成一个流
     */</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> testFlatMap <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">StreamAPI_Test</span> s <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StreamAPI_Test</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> list <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token string">&quot;aaa&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;bbb&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;ccc&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;ddd&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">flatMap</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> s<span class="token punctuation">.</span><span class="token function">filterCharacter</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">//如果使用map则需要这样写</span>
        list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> s<span class="token punctuation">.</span><span class="token function">filterCharacter</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/**
     * 将一个字符串转换为流
     */</span>
    <span class="token keyword">public</span> <span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Character</span><span class="token punctuation">&gt;</span></span> <span class="token function">filterCharacter</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Character</span><span class="token punctuation">&gt;</span></span> list <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Character</span> ch <span class="token operator">:</span> str<span class="token punctuation">.</span><span class="token function">toCharArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            list<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>ch<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br></div></div><p>其实map方法就相当于Collaction的add方法，如果add的是个集合得话就会变成二维数组，而flatMap 的话就相当于Collaction的addAll方法，参数如果是集合得话，只是将2个集合合并，而不是变成二维数组。</p> <h3 id="排序"><a href="#排序" class="header-anchor">#</a> 排序</h3> <p>关于排序相关的方法如下表所示。</p> <table><thead><tr><th>方法</th> <th style="text-align:center;">描述</th></tr></thead> <tbody><tr><td>sorted()</td> <td style="text-align:center;">产生一个新流，其中按自然顺序排序</td></tr> <tr><td>sorted(Comparator comp)</td> <td style="text-align:center;">产生一个新流，其中按比较器顺序排序</td></tr></tbody></table> <p>从上述表格可以看出：sorted有两种方法，一种是不传任何参数，叫自然排序，还有一种需要传Comparator 接口参数，叫做定制排序。</p> <p>先来看Java8中Stream接口对于sorted()方法的声明，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">sorted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">Stream</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">sorted</span><span class="token punctuation">(</span><span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> comparator<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>sorted()方法的定义比较简单，我就不再赘述了。</p> <p>我们也可以按照如下方式来使用Stream的sorted()方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">// 自然排序</span>
<span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> persons <span class="token operator">=</span> list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">sorted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">//定制排序</span>
<span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> persons1 <span class="token operator">=</span> list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">sorted</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e1<span class="token punctuation">,</span> e2<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>e1<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> e2<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>e1<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;</span> e2<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br></div></div><h3 id="stream的终止操作"><a href="#stream的终止操作" class="header-anchor">#</a> Stream的终止操作</h3> <p>终端操作会从流的流水线生成结果。其结果可以是任何不是流的值，例如： List、 Integer、Double、String等等，甚至是 void 。</p> <p>在Java8中，Stream的终止操作可以分为：查找与匹配、规约和收集。接下来，我们就分别简单说明下这些终止操作。</p> <h3 id="查找与匹配"><a href="#查找与匹配" class="header-anchor">#</a> 查找与匹配</h3> <p>Stream API中有关查找与匹配的方法如下表所示。</p> <table><thead><tr><th>方法</th> <th>描述</th></tr></thead> <tbody><tr><td>allMatch(Predicate p)</td> <td>检查是否匹配所有元素</td></tr> <tr><td>anyMatch(Predicate p)</td> <td>检查是否至少匹配一个元素</td></tr> <tr><td>noneMatch(Predicate p)</td> <td>检查是否没有匹配所有元素</td></tr> <tr><td>findFirst()</td> <td>返回第一个元素</td></tr> <tr><td>findAny()</td> <td>返回当前流中的任意元素</td></tr> <tr><td>count()</td> <td>返回流中元素总数</td></tr> <tr><td>max(Comparator c)</td> <td>返回流中最大值</td></tr> <tr><td>min(Comparator c)</td> <td>返回流中最小值</td></tr> <tr><td>forEach(Consumer c)</td> <td>内部迭代(使用 Collection 接口需要用户去做迭代，称为外部迭代。相反， Stream API 使用内部迭代)</td></tr></tbody></table> <p>同样的，我们对每个重要的方法进行简单的示例说明，这里，我们首先建立一个Employee类，Employee类的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Data</span>
<span class="token annotation punctuation">@Builder</span>
<span class="token annotation punctuation">@ToString</span>
<span class="token annotation punctuation">@NoArgsConstructor</span>
<span class="token annotation punctuation">@AllArgsConstructor</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Employee</span> <span class="token keyword">implements</span> <span class="token class-name">Serializable</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">long</span> serialVersionUID <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">9079722457749166858L</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> name<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">Integer</span> age<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">Double</span> salary<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">Stauts</span> stauts<span class="token punctuation">;</span>
    <span class="token keyword">public</span> <span class="token keyword">enum</span> <span class="token class-name">Stauts</span><span class="token punctuation">{</span>
        WORKING<span class="token punctuation">,</span>
        SLEEPING<span class="token punctuation">,</span>
        VOCATION
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div><p>接下来，我们在测试类中定义一个用于测试的集合employees，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">protected</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> employees <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;张三&quot;</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">,</span> <span class="token number">9999.99</span><span class="token punctuation">,</span> <span class="token class-name">Employee<span class="token punctuation">.</span>Stauts</span><span class="token punctuation">.</span>SLEEPING<span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;李四&quot;</span><span class="token punctuation">,</span> <span class="token number">38</span><span class="token punctuation">,</span> <span class="token number">5555.55</span><span class="token punctuation">,</span> <span class="token class-name">Employee<span class="token punctuation">.</span>Stauts</span><span class="token punctuation">.</span>WORKING<span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;王五&quot;</span><span class="token punctuation">,</span> <span class="token number">60</span><span class="token punctuation">,</span> <span class="token number">6666.66</span><span class="token punctuation">,</span> <span class="token class-name">Employee<span class="token punctuation">.</span>Stauts</span><span class="token punctuation">.</span>WORKING<span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;赵六&quot;</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">7777.77</span><span class="token punctuation">,</span> <span class="token class-name">Employee<span class="token punctuation">.</span>Stauts</span><span class="token punctuation">.</span>SLEEPING<span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token string">&quot;田七&quot;</span><span class="token punctuation">,</span> <span class="token number">58</span><span class="token punctuation">,</span> <span class="token number">3333.33</span><span class="token punctuation">,</span> <span class="token class-name">Employee<span class="token punctuation">.</span>Stauts</span><span class="token punctuation">.</span>VOCATION<span class="token punctuation">)</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>好了，准备工作就绪了。接下来，我们就开始测试Stream的每个终止方法。</p> <p><strong>1.allMatch()</strong></p> <p>allMatch()方法表示检查是否匹配所有元素。其在Stream接口中的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">boolean</span> <span class="token function">allMatch</span><span class="token punctuation">(</span><span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> predicate<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们可以通过类似如下示例来使用allMatch()方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">boolean</span> match <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">allMatch</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Employee<span class="token punctuation">.</span>Stauts</span><span class="token punctuation">.</span>SLEEPING<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>e<span class="token punctuation">.</span><span class="token function">getStauts</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>match<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>注意：使用allMatch()方法时，只有所有的元素都匹配条件时，allMatch()方法才会返回true。</strong></p> <p><strong>2.anyMatch()方法</strong></p> <p>anyMatch方法表示检查是否至少匹配一个元素。其在Stream接口中的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">boolean</span> <span class="token function">anyMatch</span><span class="token punctuation">(</span><span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> predicate<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们可以通过类似如下示例来使用anyMatch()方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">boolean</span> match <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">anyMatch</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Employee<span class="token punctuation">.</span>Stauts</span><span class="token punctuation">.</span>SLEEPING<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>e<span class="token punctuation">.</span><span class="token function">getStauts</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>match<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>注意：使用anyMatch()方法时，只要有任意一个元素符合条件，anyMatch()方法就会返回true。</strong></p> <p><strong>3.noneMatch()方法</strong></p> <p>noneMatch()方法表示检查是否没有匹配所有元素。其在Stream接口中的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">boolean</span> <span class="token function">noneMatch</span><span class="token punctuation">(</span><span class="token class-name">Predicate</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> predicate<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们可以通过类似如下示例来使用noneMatch()方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">boolean</span> match <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">noneMatch</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Employee<span class="token punctuation">.</span>Stauts</span><span class="token punctuation">.</span>SLEEPING<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>e<span class="token punctuation">.</span><span class="token function">getStauts</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>match<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>注意：使用noneMatch()方法时，只有所有的元素都不符合条件时，noneMatch()方法才会返回true。</strong></p> <p><strong>4.findFirst()方法</strong></p> <p>findFirst()方法表示返回第一个元素。其在Stream接口中的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">findFirst</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们可以通过类似如下示例来使用findFirst()方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> op <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">sorted</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e1<span class="token punctuation">,</span> e2<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Double</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>e1<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e2<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">findFirst</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>op<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>5.findAny()方法</strong></p> <p>findAny()方法表示返回当前流中的任意元素。其在Stream接口中的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">findAny</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们可以通过类似如下示例来使用findAny()方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> op <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Employee<span class="token punctuation">.</span>Stauts</span><span class="token punctuation">.</span>WORKING<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>e<span class="token punctuation">.</span><span class="token function">getStauts</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">findFirst</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>op<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>6.count()方法</strong></p> <p>count()方法表示返回流中元素总数。其在Stream接口中的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">long</span> <span class="token function">count</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们可以通过类似如下示例来使用count()方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">long</span> count <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">count</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>count<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>7.max()方法</strong></p> <p>max()方法表示返回流中最大值。其在Stream接口中的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">max</span><span class="token punctuation">(</span><span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> comparator<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们可以通过类似如下示例来使用max()方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> op <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e1<span class="token punctuation">,</span> e2<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Double</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>e1<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e2<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>op<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>8.min()方法</strong></p> <p>min()方法表示返回流中最小值。其在Stream接口中的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">min</span><span class="token punctuation">(</span><span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> comparator<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们可以通过类似如下示例来使用min()方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Double</span><span class="token punctuation">&gt;</span></span> op <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">Employee</span><span class="token operator">::</span><span class="token function">getSalary</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">min</span><span class="token punctuation">(</span><span class="token class-name">Double</span><span class="token operator">::</span><span class="token function">compare</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>op<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>9.forEach()方法</strong></p> <p>forEach()方法表示内部迭代(使用 Collection 接口需要用户去做迭代，称为外部迭代。相反， Stream API 使用内部迭代)。其在Stream接口内部的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">void</span> <span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">Consumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> action<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>我们可以通过类似如下示例来使用forEach()方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><h3 id="规约"><a href="#规约" class="header-anchor">#</a> 规约</h3> <p>Stream API中有关规约的方法如下表所示。</p> <table><thead><tr><th>方法</th> <th>描述</th></tr></thead> <tbody><tr><td>reduce(T iden, BinaryOperator b)</td> <td>可以将流中元素反复结合起来，得到一个值。 返回 T</td></tr> <tr><td>reduce(BinaryOperator b)</td> <td>可以将流中元素反复结合起来，得到一个值。 返回 Optional<T></T></td></tr></tbody></table> <p>reduce()方法在Stream接口中的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">T</span> <span class="token function">reduce</span><span class="token punctuation">(</span><span class="token class-name">T</span> identity<span class="token punctuation">,</span> <span class="token class-name">BinaryOperator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> accumulator<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">reduce</span><span class="token punctuation">(</span><span class="token class-name">BinaryOperator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> accumulator<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">U</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">U</span> <span class="token function">reduce</span><span class="token punctuation">(</span><span class="token class-name">U</span> identity<span class="token punctuation">,</span> <span class="token class-name">BiFunction</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">U</span><span class="token punctuation">,</span> <span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">,</span> <span class="token class-name">U</span><span class="token punctuation">&gt;</span></span> accumulator<span class="token punctuation">,</span> <span class="token class-name">BinaryOperator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">U</span><span class="token punctuation">&gt;</span></span> combiner<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>我们可以通过类似如下示例来使用reduce方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> list <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token number">6</span><span class="token punctuation">,</span><span class="token number">7</span><span class="token punctuation">,</span><span class="token number">8</span><span class="token punctuation">,</span><span class="token number">9</span><span class="token punctuation">,</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">Integer</span> sum <span class="token operator">=</span> list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> x <span class="token operator">+</span> y<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>sum<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;----------------------------------------&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Double</span><span class="token punctuation">&gt;</span></span> op <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">Employee</span><span class="token operator">::</span><span class="token function">getSalary</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">(</span><span class="token class-name">Double</span><span class="token operator">::</span><span class="token function">sum</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>op<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>我们也可以搜索employees列表中“张”出现的次数。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code> <span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> sum <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
   <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">Employee</span><span class="token operator">::</span><span class="token function">getName</span><span class="token punctuation">)</span>
   <span class="token punctuation">.</span><span class="token function">flatMap</span><span class="token punctuation">(</span><span class="token class-name">TestStreamAPI1</span><span class="token operator">::</span><span class="token function">filterCharacter</span><span class="token punctuation">)</span>
   <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token punctuation">(</span>ch<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>ch<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token char">'六'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
     <span class="token keyword">return</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token keyword">else</span>
     <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
   <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">(</span><span class="token class-name">Integer</span><span class="token operator">::</span><span class="token function">sum</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>sum<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p><strong>注意：上述例子使用了硬编码的方式来累加某个具体值，大家在实际工作中再优化代码。</strong></p> <h3 id="收集"><a href="#收集" class="header-anchor">#</a> 收集</h3> <table><thead><tr><th>方法</th> <th>描述</th></tr></thead> <tbody><tr><td>collect(Collector c)</td> <td>将流转换为其他形式。接收一个 Collector接口的实现，用于给Stream中元素做汇总的方法</td></tr></tbody></table> <p>collect()方法在Stream接口中的定义如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">R</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">R</span> <span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Supplier</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">R</span><span class="token punctuation">&gt;</span></span> supplier<span class="token punctuation">,</span>
              <span class="token class-name">BiConsumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">R</span><span class="token punctuation">,</span> <span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> accumulator<span class="token punctuation">,</span>
              <span class="token class-name">BiConsumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">R</span><span class="token punctuation">,</span> <span class="token class-name">R</span><span class="token punctuation">&gt;</span></span> combiner<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">R</span><span class="token punctuation">,</span> <span class="token class-name">A</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">R</span> <span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collector</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">,</span> <span class="token class-name">A</span><span class="token punctuation">,</span> <span class="token class-name">R</span><span class="token punctuation">&gt;</span></span> collector<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>我们可以通过类似如下示例来使用collect方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Double</span><span class="token punctuation">&gt;</span></span> max <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
   <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">Employee</span><span class="token operator">::</span><span class="token function">getSalary</span><span class="token punctuation">)</span>
   <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">maxBy</span><span class="token punctuation">(</span><span class="token class-name">Double</span><span class="token operator">::</span><span class="token function">compare</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>max<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> op <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
   <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">minBy</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e1<span class="token punctuation">,</span> e2<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Double</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>e1<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e2<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>op<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">Double</span> sum <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">summingDouble</span><span class="token punctuation">(</span><span class="token class-name">Employee</span><span class="token operator">::</span><span class="token function">getSalary</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>sum<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">Double</span> avg <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">averagingDouble</span><span class="token punctuation">(</span><span class="token class-name">Employee</span><span class="token operator">::</span><span class="token function">getSalary</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>avg<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">Long</span> count <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">counting</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>count<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;--------------------------------------------&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">DoubleSummaryStatistics</span> dss <span class="token operator">=</span> employees<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
   <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">summarizingDouble</span><span class="token punctuation">(</span><span class="token class-name">Employee</span><span class="token operator">::</span><span class="token function">getSalary</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>dss<span class="token punctuation">.</span><span class="token function">getMax</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div><h3 id="如何收集stream流"><a href="#如何收集stream流" class="header-anchor">#</a> 如何收集Stream流？</h3> <p>Collector接口中方法的实现决定了如何对流执行收集操作(如收集到 List、 Set、 Map)。 Collectors实用类提供了很多静态方法，可以方便地创建常见收集器实例， 具体方法与实例如下表：</p> <table><thead><tr><th>方法</th> <th>返回类型</th> <th>作用</th></tr></thead> <tbody><tr><td>toList</td> <td>List<T></T></td> <td>把流中元素收集到List</td></tr> <tr><td>toSet</td> <td>Set<T></T></td> <td>把流中元素收集到Set</td></tr> <tr><td>toCollection</td> <td>Collection<T></T></td> <td>把流中元素收集到创建的集合</td></tr> <tr><td>counting</td> <td>Long</td> <td>计算流中元素的个数</td></tr> <tr><td>summingInt</td> <td>Integer</td> <td>对流中元素的整数属性求和</td></tr> <tr><td>averagingInt</td> <td>Double</td> <td>计算流中元素Integer属性的平均 值</td></tr> <tr><td>summarizingInt</td> <td>IntSummaryStatistics</td> <td>收集流中Integer属性的统计值。 如：平均值</td></tr> <tr><td>joining</td> <td>String</td> <td>连接流中每个字符串</td></tr> <tr><td>maxBy</td> <td>Optional<T></T></td> <td>根据比较器选择最大值</td></tr> <tr><td>minBy</td> <td>Optional<T></T></td> <td>根据比较器选择最小值</td></tr> <tr><td>reducing</td> <td>归约产生的类型</td> <td>从一个作为累加器的初始值 开始，利用BinaryOperator与 流中元素逐个结合，从而归 约成单个值</td></tr> <tr><td>collectingAndThen</td> <td>转换函数返回的类型</td> <td>包裹另一个收集器，对其结 果转换函数</td></tr> <tr><td>groupingBy</td> <td>Map&lt;K, List<T>&gt;</T></td> <td>根据某属性值对流分组，属 性为K，结果为V</td></tr> <tr><td>partitioningBy</td> <td>Map&lt;Boolean, List<T>&gt;</T></td> <td>根据true或false进行分区</td></tr></tbody></table> <p>每个方法对应的使用示例如下表所示。</p> <table><thead><tr><th>方法</th> <th>使用示例</th></tr></thead> <tbody><tr><td>toList</td> <td>List<Employee> employees= list.stream().collect(Collectors.toList());</Employee></td></tr> <tr><td>toSet</td> <td>Set<Employee> employees= list.stream().collect(Collectors.toSet());</Employee></td></tr> <tr><td>toCollection</td> <td>Collection<Employee> employees=list.stream().collect(Collectors.toCollection(ArrayList::new));</Employee></td></tr> <tr><td>counting</td> <td>long count = list.stream().collect(Collectors.counting());</td></tr> <tr><td>summingInt</td> <td>int total=list.stream().collect(Collectors.summingInt(Employee::getSalary));</td></tr> <tr><td>averagingInt</td> <td>double avg= list.stream().collect(Collectors.averagingInt(Employee::getSalary))</td></tr> <tr><td>summarizingInt</td> <td>IntSummaryStatistics iss= list.stream().collect(Collectors.summarizingInt(Employee::getSalary));</td></tr> <tr><td>Collectors</td> <td>String str= list.stream().map(Employee::getName).collect(Collectors.joining());</td></tr> <tr><td>maxBy</td> <td>Optional<Emp>max= list.stream().collect(Collectors.maxBy(comparingInt(Employee::getSalary)))；</Emp></td></tr> <tr><td>minBy</td> <td>Optional<Emp> min = list.stream().collect(Collectors.minBy(comparingInt(Employee::getSalary)));</Emp></td></tr> <tr><td>reducing</td> <td>int total=list.stream().collect(Collectors.reducing(0, Employee::getSalar, Integer::sum));</td></tr> <tr><td>collectingAndThen</td> <td>int how= list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), List::size));</td></tr> <tr><td>groupingBy</td> <td>Map&lt;Emp.Status, List<Emp>&gt; map= list.stream() .collect(Collectors.groupingBy(Employee::getStatus));</Emp></td></tr> <tr><td>partitioningBy</td> <td>Map&lt;Boolean,List<Emp>&gt;vd= list.stream().collect(Collectors.partitioningBy(Employee::getManage));</Emp></td></tr></tbody></table> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test4</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Double</span><span class="token punctuation">&gt;</span></span> max <span class="token operator">=</span> emps<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">Employee</span><span class="token operator">::</span><span class="token function">getSalary</span><span class="token punctuation">)</span>
        <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">maxBy</span><span class="token punctuation">(</span><span class="token class-name">Double</span><span class="token operator">::</span><span class="token function">compare</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>max<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">&gt;</span></span> op <span class="token operator">=</span> emps<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">minBy</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e1<span class="token punctuation">,</span> e2<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">Double</span><span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>e1<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e2<span class="token punctuation">.</span><span class="token function">getSalary</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>op<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token class-name">Double</span> sum <span class="token operator">=</span> emps<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">summingDouble</span><span class="token punctuation">(</span><span class="token class-name">Employee</span><span class="token operator">::</span><span class="token function">getSalary</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>sum<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token class-name">Double</span> avg <span class="token operator">=</span> emps<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collecors</span><span class="token punctuation">.</span><span class="token function">averagingDouble</span><span class="token punctuation">(</span><span class="token class-name">Employee</span><span class="token operator">::</span><span class="token function">getSalary</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>avg<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">Long</span> count <span class="token operator">=</span> emps<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">counting</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token class-name">DoubleSummaryStatistics</span> dss <span class="token operator">=</span> emps<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">summarizingDouble</span><span class="token punctuation">(</span><span class="token class-name">Employee</span><span class="token operator">::</span><span class="token function">getSalary</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>dss<span class="token punctuation">.</span><span class="token function">getMax</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br></div></div><h3 id="什么是并行流"><a href="#什么是并行流" class="header-anchor">#</a> 什么是并行流？</h3> <p>简单来说，并行流就是把一个内容分成多个数据块，并用不同的线程分别处理每个数据块的流。</p> <p>Java 8 中将并行进行了优化，我们可以很容易的对数据进行并行操作。 Stream API 可以声明性地通过 parallel() 与sequential() 在并行流与顺序流之间进行切换 。</p> <h3 id="fork-join-框架-2"><a href="#fork-join-框架-2" class="header-anchor">#</a> Fork/Join 框架</h3> <p>Fork/Join 框架： 就是在必要的情况下，将一个大任务，进行拆分(fork)成若干个小任务（拆到不可再拆时），再将一个个的小任务运算的结果进行 join 汇总 。</p> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314195236981.jpg" loading="lazy" class="lazy"></p> <h3 id="fork-join-框架与传统线程池有啥区别"><a href="#fork-join-框架与传统线程池有啥区别" class="header-anchor">#</a> Fork/Join 框架与传统线程池有啥区别？</h3> <p>采用 “工作窃取”模式（work-stealing）：</p> <p>当执行新的任务时它可以将其拆分成更小的任务执行，并将小任务加到线程队列中，然后再从一个随机线程的队列中偷一个并把它放在自己的队列中。</p> <p>相对于一般的线程池实现，fork/join框架的优势体现在对其中包含的任务的处理方式上。在一般的线程池中，如果一个线程正在执行的任务由于某些原因无法继续运行，那么该线程会处于等待状态。而在fork/join框架的实现中，如果某个子任务由于等待另外一个子任务的完成而无法继续运行。那么处理该子问题的线程会主动寻找其他尚未运行的子任务来执行。这种方式减少了线程的等待时间，提高了程序的性能。</p> <h3 id="fork-join框架实例"><a href="#fork-join框架实例" class="header-anchor">#</a> Fork/Join框架实例</h3> <p>了解了ForJoin框架的原理之后，我们就来手动写一个使用Fork/Join框架实现累加和的示例程序，以帮助读者更好的理解Fork/Join框架。好了，不废话了，上代码，大家通过下面的代码好好体会下Fork/Join框架的强大。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">package</span> <span class="token namespace">io<span class="token punctuation">.</span>binghe<span class="token punctuation">.</span>concurrency<span class="token punctuation">.</span>example<span class="token punctuation">.</span>aqs</span><span class="token punctuation">;</span>
 
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">lombok<span class="token punctuation">.</span>extern<span class="token punctuation">.</span>slf4j<span class="token punctuation">.</span></span><span class="token class-name">Slf4j</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span><span class="token class-name">ForkJoinPool</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span><span class="token class-name">Future</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span><span class="token class-name">RecursiveTask</span></span><span class="token punctuation">;</span>
<span class="token annotation punctuation">@Slf4j</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ForkJoinTaskExample</span> <span class="token keyword">extends</span> <span class="token class-name">RecursiveTask</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">int</span> threshold <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> start<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> end<span class="token punctuation">;</span>
    <span class="token keyword">public</span> <span class="token class-name">ForkJoinTaskExample</span><span class="token punctuation">(</span><span class="token keyword">int</span> start<span class="token punctuation">,</span> <span class="token keyword">int</span> end<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>start <span class="token operator">=</span> start<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>end <span class="token operator">=</span> end<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">protected</span> <span class="token class-name">Integer</span> <span class="token function">compute</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">int</span> sum <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token comment">//如果任务足够小就计算任务</span>
        <span class="token keyword">boolean</span> canCompute <span class="token operator">=</span> <span class="token punctuation">(</span>end <span class="token operator">-</span> start<span class="token punctuation">)</span> <span class="token operator">&lt;=</span> threshold<span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>canCompute<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> start<span class="token punctuation">;</span> i <span class="token operator">&lt;=</span> end<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                sum <span class="token operator">+=</span> i<span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            <span class="token comment">// 如果任务大于阈值，就分裂成两个子任务计算</span>
            <span class="token keyword">int</span> middle <span class="token operator">=</span> <span class="token punctuation">(</span>start <span class="token operator">+</span> end<span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">;</span>
            <span class="token class-name">ForkJoinTaskExample</span> leftTask <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ForkJoinTaskExample</span><span class="token punctuation">(</span>start<span class="token punctuation">,</span> middle<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">ForkJoinTaskExample</span> rightTask <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ForkJoinTaskExample</span><span class="token punctuation">(</span>middle <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span> end<span class="token punctuation">)</span><span class="token punctuation">;</span>
 
            <span class="token comment">// 执行子任务</span>
            leftTask<span class="token punctuation">.</span><span class="token function">fork</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            rightTask<span class="token punctuation">.</span><span class="token function">fork</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 
            <span class="token comment">// 等待任务执行结束合并其结果</span>
            <span class="token keyword">int</span> leftResult <span class="token operator">=</span> leftTask<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">int</span> rightResult <span class="token operator">=</span> rightTask<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 
            <span class="token comment">// 合并子任务</span>
            sum <span class="token operator">=</span> leftResult <span class="token operator">+</span> rightResult<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> sum<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">ForkJoinPool</span> forkjoinPool <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ForkJoinPool</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 
        <span class="token comment">//生成一个计算任务，计算1+2+3+4</span>
        <span class="token class-name">ForkJoinTaskExample</span> task <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ForkJoinTaskExample</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 
        <span class="token comment">//执行一个任务</span>
        <span class="token class-name">Future</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> result <span class="token operator">=</span> forkjoinPool<span class="token punctuation">.</span><span class="token function">submit</span><span class="token punctuation">(</span>task<span class="token punctuation">)</span><span class="token punctuation">;</span>
 
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">&quot;result:{}&quot;</span><span class="token punctuation">,</span> result<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">&quot;exception&quot;</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br><span class="line-number">44</span><br><span class="line-number">45</span><br><span class="line-number">46</span><br><span class="line-number">47</span><br><span class="line-number">48</span><br><span class="line-number">49</span><br><span class="line-number">50</span><br><span class="line-number">51</span><br><span class="line-number">52</span><br><span class="line-number">53</span><br><span class="line-number">54</span><br><span class="line-number">55</span><br><span class="line-number">56</span><br><span class="line-number">57</span><br><span class="line-number">58</span><br><span class="line-number">59</span><br></div></div><h3 id="java8中的并行流实例"><a href="#java8中的并行流实例" class="header-anchor">#</a> Java8中的并行流实例</h3> <p>Java8对并行流进行了大量的优化，并且在开发上也极大的简化了程序员的工作量，我们只需要使用类似如下的代码就可以使用Java8中的并行流来处理我们的数据。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">LongStream</span><span class="token punctuation">.</span><span class="token function">rangeClosed</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">10000000L</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">parallel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token class-name">Long</span><span class="token operator">::</span><span class="token function">sum</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>在Java8中如何优雅的切换并行流和串行流呢？</strong></p> <p>Stream API 可以声明性地通过 parallel() 与sequential() 在并行流与串行流之间进行切换 。</p> <h2 id="optional类"><a href="#optional类" class="header-anchor">#</a> Optional类</h2> <h3 id="什么是optional类"><a href="#什么是optional类" class="header-anchor">#</a> 什么是Optional类？</h3> <p>Optional<T> 类(java.util.Optional) 是一个容器类，代表一个值存在或不存在，原来用 null 表示一个值不存在，现在 Optional 可以更好的表达这个概念。并且可以避免空指针异常。</T></p> <p><strong>Optional类常用方法：</strong></p> <ul><li><p>Optional.of(T t) : 创建一个 Optional 实例。</p></li> <li><p>Optional.empty() : 创建一个空的 Optional 实例。</p></li> <li><p>Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例。</p></li> <li><p>isPresent() : 判断是否包含值。</p></li> <li><p>orElse(T t) : 如果调用对象包含值，返回该值，否则返回t。</p></li> <li><p>orElseGet(Supplier s) :如果调用对象包含值，返回该值，否则返回 s 获取的值。</p></li> <li><p>map(Function f): 如果有值对其处理，并返回处理后的Optional，否则返回 Optional.empty()。</p></li> <li><p>flatMap(Function mapper):与 map 类似，要求返回值必须是Optional。</p></li></ul> <h3 id="optional类示例"><a href="#optional类示例" class="header-anchor">#</a> Optional类示例</h3> <p><strong>1.创建Optional类</strong></p> <p>（1）使用empty()方法创建一个空的Optional对象：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> empty <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">empty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>（2）使用of()方法创建Optional对象：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">String</span> name <span class="token operator">=</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">;</span>
<span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> opt <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token string">&quot;Optional[binghe]&quot;</span><span class="token punctuation">,</span> opt<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>传递给of()的值不可以为空，否则会抛出空指针异常。例如，下面的程序会抛出空指针异常。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">String</span> name <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
<span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> opt <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>如果我们需要传递一些空值，那我们可以使用下面的示例所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">String</span> name <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
<span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> opt <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>使用ofNullable()方法，则当传递进去一个空值时，不会抛出异常，而只是返回一个空的Optional对象，如同我们用Optional.empty()方法一样。</p> <p><strong>2.isPresent</strong></p> <p>我们可以使用这个isPresent()方法检查一个Optional对象中是否有值，只有值非空才返回true。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> opt <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertTrue</span><span class="token punctuation">(</span>opt<span class="token punctuation">.</span><span class="token function">isPresent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

opt <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertFalse</span><span class="token punctuation">(</span>opt<span class="token punctuation">.</span><span class="token function">isPresent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>在Java8之前，我们一般使用如下方式来检查空值。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">if</span><span class="token punctuation">(</span>name <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>name<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>在Java8中，我们就可以使用如下方式来检查空值了。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> opt <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
opt<span class="token punctuation">.</span><span class="token function">ifPresent</span><span class="token punctuation">(</span>name <span class="token operator">-&gt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>name<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>3.orElse和orElseGet</strong></p> <p>（1）orElse</p> <p>orElse()方法用来返回Optional对象中的默认值，它被传入一个“默认参数‘。如果对象中存在一个值，则返回它，否则返回传入的“默认参数”。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">String</span> nullName <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> name <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>nullName<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">orElse</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>（2）orElseGet</p> <p>与orElse()方法类似，但是这个函数不接收一个“默认参数”，而是一个函数接口。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">String</span> nullName <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> name <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>nullName<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">orElseGet</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>（3）二者有什么区别？</p> <p>要想理解二者的区别，首先让我们创建一个无参且返回定值的方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getDefaultName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;Getting Default Name&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>接下来，进行两个测试看看两个方法到底有什么区别。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">String</span> text<span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;Using orElseGet:&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> defaultText <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>text<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">orElseGet</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token operator">::</span><span class="token function">getDefaultName</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> defaultText<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;Using orElse:&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
defaultText <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>text<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">orElse</span><span class="token punctuation">(</span><span class="token function">getDefaultName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> defaultText<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>在这里示例中，我们的Optional对象中包含的都是一个空值，让我们看看程序执行结果:</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Using</span> orElseGet<span class="token operator">:</span>
<span class="token class-name">Getting</span> <span class="token keyword">default</span> name<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token class-name">Using</span> orElse<span class="token operator">:</span>
<span class="token class-name">Getting</span> <span class="token keyword">default</span> name<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>两个Optional对象中都不存在value，因此执行结果相同。</p> <p>那么，当Optional对象中存在数据会发生什么呢？我们一起来验证下。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">String</span> name <span class="token operator">=</span> <span class="token string">&quot;binghe001&quot;</span><span class="token punctuation">;</span>

<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;Using orElseGet:&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> defaultName <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">orElseGet</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token operator">::</span><span class="token function">getDefaultName</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token string">&quot;binghe001&quot;</span><span class="token punctuation">,</span> defaultName<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;Using orElse:&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
defaultName <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">orElse</span><span class="token punctuation">(</span><span class="token function">getDefaultName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token string">&quot;binghe001&quot;</span><span class="token punctuation">,</span> defaultName<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><p>运行结果如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Using</span> orElseGet<span class="token operator">:</span>
<span class="token class-name">Using</span> orElse<span class="token operator">:</span>
<span class="token class-name">Getting</span> <span class="token keyword">default</span> name<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>可以看到，当使用orElseGet()方法时，getDefaultName()方法并不执行，因为Optional中含有值，而使用orElse时则照常执行。所以可以看到，当值存在时，orElse相比于orElseGet，多创建了一个对象。如果创建对象时，存在网络交互，那系统资源的开销就比较大了，这是需要我们注意的一个地方。</p> <p><strong>4.orElseThrow</strong></p> <p>orElseThrow()方法当遇到一个不存在的值的时候，并不返回一个默认值，而是抛出异常。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">String</span> nullName <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> name <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>nullName<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">orElseThrow</span><span class="token punctuation">(</span> <span class="token class-name">IllegalArgumentException</span><span class="token operator">::</span><span class="token keyword">new</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>5.get</strong></p> <p>get()方法表示是Optional对象中获取值。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> opt <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> name <span class="token operator">=</span> opt<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>使用get()方法也可以返回被包裹着的值。但是值必须存在。当值不存在时，会抛出一个NoSuchElementException异常。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> opt <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> name <span class="token operator">=</span> opt<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>6.filter</strong></p> <p>接收一个函数式接口，当符合接口时，则返回一个Optional对象，否则返回一个空的Optional对象。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">String</span> name <span class="token operator">=</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">;</span>
<span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> nameOptional <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">boolean</span> isBinghe <span class="token operator">=</span> nameOptional<span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>n <span class="token operator">-&gt;</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isPresent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertTrue</span><span class="token punctuation">(</span>isBinghe<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">boolean</span> isBinghe001 <span class="token operator">=</span> nameOptional<span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>n <span class="token operator">-&gt;</span> <span class="token string">&quot;binghe001&quot;</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isPresent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertFalse</span><span class="token punctuation">(</span>isBinghe001<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>使用filter()方法会过滤掉我们不需要的元素。</p> <p>接下来，我们再来看一例示例，例如目前有一个Person类，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Person</span><span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> age<span class="token punctuation">;</span>
    <span class="token keyword">public</span> <span class="token class-name">Person</span><span class="token punctuation">(</span><span class="token keyword">int</span> age<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>age <span class="token operator">=</span> age<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token comment">//省略get set方法</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>例如，我们需要过滤出年龄在25岁到35岁之前的人群，那在Java8之前我们需要创建一个如下的方法来检测每个人的年龄范围是否在25岁到35岁之前。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">filterPerson</span><span class="token punctuation">(</span><span class="token class-name">Peron</span> person<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">boolean</span> isInRange <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>person <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> person<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number">25</span> <span class="token operator">&amp;&amp;</span> person<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;=</span> <span class="token number">35</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        isInRange <span class="token operator">=</span>  <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> isInRange<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>看上去就挺麻烦的，我们可以使用如下的方式进行测试。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token function">assertTrue</span><span class="token punctuation">(</span><span class="token function">filterPerson</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Peron</span><span class="token punctuation">(</span><span class="token number">18</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertFalse</span><span class="token punctuation">(</span><span class="token function">filterPerson</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Peron</span><span class="token punctuation">(</span><span class="token number">29</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertFalse</span><span class="token punctuation">(</span><span class="token function">filterPerson</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Peron</span><span class="token punctuation">(</span><span class="token number">16</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertFalse</span><span class="token punctuation">(</span><span class="token function">filterPerson</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Peron</span><span class="token punctuation">(</span><span class="token number">34</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertFalse</span><span class="token punctuation">(</span><span class="token function">filterPerson</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>如果使用Optional，效果如何呢？</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">filterPersonByOptional</span><span class="token punctuation">(</span><span class="token class-name">Peron</span> person<span class="token punctuation">)</span><span class="token punctuation">{</span>
     <span class="token keyword">return</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>person<span class="token punctuation">)</span>
       <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">Peron</span><span class="token operator">::</span><span class="token function">getAge</span><span class="token punctuation">)</span>
       <span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>p <span class="token operator">-&gt;</span> p <span class="token operator">&gt;=</span> <span class="token number">25</span><span class="token punctuation">)</span>
       <span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>p <span class="token operator">-&gt;</span> p <span class="token operator">&lt;=</span> <span class="token number">35</span><span class="token punctuation">)</span>
       <span class="token punctuation">.</span><span class="token function">isPresent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>使用Optional看上去就清爽多了，这里，map()仅仅是将一个值转换为另一个值，并且这个操作并不会改变原来的值。</p> <p><strong>7.map</strong></p> <p>如果有值对其处理，并返回处理后的Optional，否则返回 Optional.empty()。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> names <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token string">&quot;binghe001&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;binghe002&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;binghe003&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;binghe004&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">List</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span><span class="token punctuation">&gt;</span></span> listOptional <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span>names<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">int</span> size <span class="token operator">=</span> listOptional
    <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">List</span><span class="token operator">::</span><span class="token function">size</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">orElse</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">,</span> size<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>在这个例子中，我们使用一个List集合封装了一些字符串，然后再把这个List使用Optional封装起来，对其map()，获取List集合的长度。map()返回的结果也被封装在一个Optional对象中，这里当值不存在的时候，我们会默认返回0。如下我们获取一个字符串的长度。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">String</span> name <span class="token operator">=</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">;</span>
<span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> nameOptional <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">int</span> len <span class="token operator">=</span> nameOptional
    <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token operator">::</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">orElse</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">,</span> len<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>我们也可以将map()方法与filter()方法结合使用，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">String</span> password <span class="token operator">=</span> <span class="token string">&quot; password &quot;</span><span class="token punctuation">;</span>
<span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> passOpt <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span>password<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">boolean</span> correctPassword <span class="token operator">=</span> passOpt<span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>
    pass <span class="token operator">-&gt;</span> pass<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token string">&quot;password&quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isPresent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertFalse</span><span class="token punctuation">(</span>correctPassword<span class="token punctuation">)</span><span class="token punctuation">;</span>

correctPassword <span class="token operator">=</span> passOpt
    <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token operator">::</span><span class="token function">trim</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>pass <span class="token operator">-&gt;</span> pass<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token string">&quot;password&quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">isPresent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertTrue</span><span class="token punctuation">(</span>correctPassword<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p>上述代码的含义就是对密码进行验证，查看密码是否为指定的值。</p> <p><strong>8.flatMap</strong></p> <p>与 map 类似，要求返回值必须是Optional。</p> <p>假设我们现在有一个Person类。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Person</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> name<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> age<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> password<span class="token punctuation">;</span>
 
    <span class="token keyword">public</span> <span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
 
    <span class="token keyword">public</span> <span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> <span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>age<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
 
    <span class="token keyword">public</span> <span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> <span class="token function">getPassword</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">ofNullable</span><span class="token punctuation">(</span>password<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token comment">// 忽略get set方法</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br></div></div><p>接下来，我们可以将Person封装到Optional中，并进行测试，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Person</span> person <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Person</span><span class="token punctuation">&gt;</span></span> personOptional <span class="token operator">=</span> <span class="token class-name">Optional</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span>person<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Optional</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span><span class="token punctuation">&gt;</span></span> nameOptionalWrapper <span class="token operator">=</span> personOptional<span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">Person</span><span class="token operator">::</span><span class="token function">getName</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">Optional</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> nameOptional <span class="token operator">=</span> nameOptionalWrapper<span class="token punctuation">.</span><span class="token function">orElseThrow</span><span class="token punctuation">(</span><span class="token class-name">IllegalArgumentException</span><span class="token operator">::</span><span class="token keyword">new</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> name1 <span class="token operator">=</span> nameOptional<span class="token punctuation">.</span><span class="token function">orElse</span><span class="token punctuation">(</span><span class="token string">&quot;&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> name1<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token class-name">String</span> name <span class="token operator">=</span> personOptional
    <span class="token punctuation">.</span><span class="token function">flatMap</span><span class="token punctuation">(</span><span class="token class-name">Person</span><span class="token operator">::</span><span class="token function">getName</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">orElse</span><span class="token punctuation">(</span><span class="token string">&quot;&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">assertEquals</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">,</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p>注意：方法getName返回的是一个Optional对象，如果使用map，我们还需要再调用一次get()方法，而使用flatMap()就不需要了。</p> <h2 id="默认方法"><a href="#默认方法" class="header-anchor">#</a> 默认方法</h2> <h3 id="接口中的默认方法"><a href="#接口中的默认方法" class="header-anchor">#</a> 接口中的默认方法</h3> <p>Java 8中允许接口中包含具有具体实现的方法，该方法称为“默认方法”，默认方法使用 default 关键字修饰 。</p> <p>例如，我们可以定义一个接口MyFunction，其中，包含有一个默认方法getName，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">MyFunction</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">{</span>
    <span class="token class-name">T</span> <span class="token function">get</span><span class="token punctuation">(</span><span class="token class-name">Long</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">default</span> <span class="token class-name">String</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><h3 id="默认方法的原则"><a href="#默认方法的原则" class="header-anchor">#</a> 默认方法的原则</h3> <p>在Java8中，默认方法具有“类优先”的原则。</p> <p>若一个接口中定义了一个默认方法，而另外一个父类或接口中又定义了一个同名的方法时，遵循如下的原则。</p> <p><strong>1.选择父类中的方法。如果一个父类提供了具体的实现，那么接口中具有相同名称和参数的默认方法会被忽略。</strong></p> <p>例如，现在有一个接口为MyFunction，和一个类MyClass，如下所示。</p> <ul><li>MyFunction接口</li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">MyFunction</span><span class="token punctuation">{</span>
    <span class="token keyword">default</span> <span class="token class-name">String</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">&quot;MyFunction&quot;</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><ul><li>MyClass类</li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyClass</span><span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">&quot;MyClass&quot;</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>此时，创建SubClass类继承MyClass类，并实现MyFunction接口，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SubClass</span> <span class="token keyword">extends</span> <span class="token class-name">MyClass</span> <span class="token keyword">implements</span> <span class="token class-name">MyFunction</span><span class="token punctuation">{</span>
    
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>接下来，我们创建一个SubClassTest类，对SubClass类进行测试，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SubClassTest</span><span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testDefaultFunction</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">SubClass</span> subClass <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SubClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>subClass<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>运行上述程序，会输出字符串：MyClass。</p> <p><strong>2.接口冲突。如果一个父接口提供一个默认方法，而另一个接口也提供了一个具有相同名称和参数列表的方法（不管方法是否是默认方法）， 那么必须覆盖该方法来解决冲突。</strong></p> <p>例如，现在有两个接口，分别为MyFunction和MyInterface，各自都有一个默认方法getName()，如下所示。</p> <ul><li>MyFunction接口</li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">MyFunction</span><span class="token punctuation">{</span>
    <span class="token keyword">default</span> <span class="token class-name">String</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">&quot;function&quot;</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><ul><li>MyInterface接口</li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">MyInterface</span><span class="token punctuation">{</span>
    <span class="token keyword">default</span> <span class="token class-name">String</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">&quot;interface&quot;</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>实现类MyClass同时实现了MyFunction接口和MyInterface接口，由于MyFunction接口和MyInterface接口中都存在getName()默认方法，所以，MyClass必须覆盖getName()方法来解决冲突，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyClass</span><span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">MyInterface</span><span class="token punctuation">.</span><span class="token keyword">super</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>此时，MyClass类中的getName方法返回的是：interface。</p> <p>如果MyClass中的getName()方法覆盖的是MyFunction接口的getName()方法，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyClass</span><span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">MyFunction</span><span class="token punctuation">.</span><span class="token keyword">super</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>此时，MyClass类中的getName方法返回的是：function。</p> <h3 id="接口中的静态方法"><a href="#接口中的静态方法" class="header-anchor">#</a> 接口中的静态方法</h3> <p>在Java8中，接口中允许添加静态方法，使用方式接口名.方法名。例如MyFunction接口中定义了静态方法send()。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">MyFunction</span><span class="token punctuation">{</span>
    <span class="token keyword">default</span> <span class="token class-name">String</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">&quot;binghe&quot;</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;Send Message...&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>我们可以直接使用如下方式调用MyFunction接口的send静态方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">MyFunction</span><span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><h2 id="本地时间和时间戳"><a href="#本地时间和时间戳" class="header-anchor">#</a> 本地时间和时间戳</h2> <p><strong>主要方法：</strong></p> <ul><li>now：静态方法，根据当前时间创建对象</li> <li>of：静态方法，根据指定日期/时间创建对象</li> <li>plusDays,plusWeeks,plusMonths,plusYears：向当前LocalDate 对象添加几天、几周、几个月、几年</li> <li>minusDays,minusWeeks,minusMonths,minusYears：从当前LocalDate 对象减去几天、几周、几个月、几年</li> <li>plus,minus：添加或减少一个Duration 或Period</li> <li>withDayOfMonth,withDayOfYear,withMonth,withYear：将月份天数、年份天数、月份、年份修改为指定的值并返回新的LocalDate 对象</li> <li>getDayOfYear：获得年份天数(1~366)</li> <li>getDayOfWeek：获得星期几(返回一个DayOfWeek枚举值)</li> <li>getMonth：获得月份, 返回一个Month 枚举值</li> <li>getMonthValue：获得月份(1~12)</li> <li>getYear：获得年份</li> <li>until：获得两个日期之间的Period 对象，或者指定ChronoUnits 的数字</li> <li>isBefore,isAfter：比较两个LocalDate</li> <li>isLeapYear：判断是否是闰年</li></ul> <h3 id="使用-localdate、-localtime、-localdatetime"><a href="#使用-localdate、-localtime、-localdatetime" class="header-anchor">#</a> 使用 LocalDate、 LocalTime、 LocalDateTime</h3> <p>LocalDate、 LocalTime、 LocalDateTime 类的实例是不可变的对象，分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的日期或时间，并不包含当前的时间信息。也不包含与时区相关的信息。</p> <blockquote><p>注： ISO-8601日历系统是国际标准化组织制定的现代公民的日期和时间的表示法</p></blockquote> <table><thead><tr><th>方法</th> <th>描述</th></tr></thead> <tbody><tr><td>now()</td> <td>静态方法，根据当前时间创建对象</td></tr> <tr><td>of()</td> <td>静态方法，根据指定日期/时间创建 对象</td></tr> <tr><td>plusDays, plusWeeks, plusMonths, plusYears</td> <td>向当前 LocalDate 对象添加几天、 几周、 几个月、 几年</td></tr> <tr><td>minusDays, minusWeeks, minusMonths, minusYears</td> <td>从当前 LocalDate 对象减去几天、 几周、 几个月、 几年</td></tr> <tr><td>plus, minus</td> <td>添加或减少一个 Duration 或 Period</td></tr> <tr><td>withDayOfMonth, withDayOfYear, withMonth, withYear</td> <td>将月份天数、 年份天数、 月份、 年 份 修 改 为 指 定 的 值 并 返 回 新 的 LocalDate 对象</td></tr> <tr><td>getDayOfMonth</td> <td>获得月份天数(1-31)</td></tr> <tr><td>getDayOfYear</td> <td>获得年份天数(1-366)</td></tr> <tr><td>getDayOfWeek</td> <td>获得星期几(返回一个 DayOfWeek 枚举值)</td></tr> <tr><td>getMonth</td> <td>获得月份, 返回一个 Month 枚举值</td></tr> <tr><td>getMonthValue</td> <td>获得月份(1-12)</td></tr> <tr><td>getYear</td> <td>获得年份</td></tr> <tr><td>until</td> <td>获得两个日期之间的 Period 对象， 或者指定 ChronoUnits 的数字</td></tr> <tr><td>isBefore, isAfter</td> <td>比较两个 LocalDate</td></tr> <tr><td>isLeapYear</td> <td>判断是否是闰年</td></tr></tbody></table> <p>示例代码如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">// 获取当前系统时间</span>
<span class="token class-name">LocalDateTime</span> localDateTime1 <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：2019-10-27T13:49:09.483</span>

<span class="token comment">// 指定日期时间</span>
<span class="token class-name">LocalDateTime</span> localDateTime2 <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">2019</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">27</span><span class="token punctuation">,</span> <span class="token number">13</span><span class="token punctuation">,</span> <span class="token number">45</span><span class="token punctuation">,</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：2019-10-27T13:45:10</span>

<span class="token class-name">LocalDateTime</span> localDateTime3 <span class="token operator">=</span> localDateTime1
        <span class="token comment">// 加三年</span>
        <span class="token punctuation">.</span><span class="token function">plusYears</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>
        <span class="token comment">// 减三个月</span>
        <span class="token punctuation">.</span><span class="token function">minusMonths</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime3<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：2022-07-27T13:49:09.483</span>

<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime1<span class="token punctuation">.</span><span class="token function">getYear</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>       <span class="token comment">// 运行结果：2019</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime1<span class="token punctuation">.</span><span class="token function">getMonthValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 运行结果：10</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime1<span class="token punctuation">.</span><span class="token function">getDayOfMonth</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 运行结果：27</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime1<span class="token punctuation">.</span><span class="token function">getHour</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>       <span class="token comment">// 运行结果：13</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime1<span class="token punctuation">.</span><span class="token function">getMinute</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment">// 运行结果：52</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime1<span class="token punctuation">.</span><span class="token function">getSecond</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment">// 运行结果：6</span>

<span class="token class-name">LocalDateTime</span> localDateTime4 <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime4<span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment">// 2019-10-27T14:19:56.884</span>
<span class="token class-name">LocalDateTime</span> localDateTime5 <span class="token operator">=</span> localDateTime4<span class="token punctuation">.</span><span class="token function">withDayOfMonth</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime5<span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment">// 2019-10-10T14:19:56.884</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br></div></div><h3 id="instant-时间戳"><a href="#instant-时间戳" class="header-anchor">#</a> Instant 时间戳</h3> <p>用于“时间戳”的运算。它是以Unix元年(传统的设定为UTC时区1970年1月1日午夜时分)开始所经历的描述进行运算 。</p> <p>示例代码如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Instant</span> instant1 <span class="token operator">=</span> <span class="token class-name">Instant</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token comment">// 默认获取UTC时区</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>instant1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：2019-10-27T05:59:58.221Z</span>

<span class="token comment">// 偏移量运算</span>
<span class="token class-name">OffsetDateTime</span> offsetDateTime <span class="token operator">=</span> instant1<span class="token punctuation">.</span><span class="token function">atOffset</span><span class="token punctuation">(</span><span class="token class-name">ZoneOffset</span><span class="token punctuation">.</span><span class="token function">ofHours</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>offsetDateTime<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：2019-10-27T13:59:58.221+08:00</span>

<span class="token comment">// 获取时间戳</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>instant1<span class="token punctuation">.</span><span class="token function">toEpochMilli</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：1572156145000</span>

<span class="token comment">// 以Unix元年为起点，进行偏移量运算</span>
<span class="token class-name">Instant</span> instant2 <span class="token operator">=</span> <span class="token class-name">Instant</span><span class="token punctuation">.</span><span class="token function">ofEpochSecond</span><span class="token punctuation">(</span><span class="token number">60</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>instant2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：1970-01-01T00:01:00Z</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div><h3 id="duration-和-period"><a href="#duration-和-period" class="header-anchor">#</a> Duration 和 Period</h3> <p>Duration:用于计算两个“时间”间隔。</p> <p>Period:用于计算两个“日期”间隔 。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Instant</span> instant_1 <span class="token operator">=</span> <span class="token class-name">Instant</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">try</span> <span class="token punctuation">{</span>
    <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token class-name">Instant</span> instant_2 <span class="token operator">=</span> <span class="token class-name">Instant</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token class-name">Duration</span> duration <span class="token operator">=</span> <span class="token class-name">Duration</span><span class="token punctuation">.</span><span class="token function">between</span><span class="token punctuation">(</span>instant_1<span class="token punctuation">,</span> instant_2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>duration<span class="token punctuation">.</span><span class="token function">toMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：1000</span>

<span class="token class-name">LocalTime</span> localTime_1 <span class="token operator">=</span> <span class="token class-name">LocalTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">try</span> <span class="token punctuation">{</span>
    <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token class-name">LocalTime</span> localTime_2 <span class="token operator">=</span> <span class="token class-name">LocalTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">Duration</span><span class="token punctuation">.</span><span class="token function">between</span><span class="token punctuation">(</span>localTime_1<span class="token punctuation">,</span> localTime_2<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：1000</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br></div></div><div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">LocalDate</span> localDate_1 <span class="token operator">=</span> <span class="token class-name">LocalDate</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">2018</span><span class="token punctuation">,</span><span class="token number">9</span><span class="token punctuation">,</span> <span class="token number">9</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">LocalDate</span> localDate_2 <span class="token operator">=</span> <span class="token class-name">LocalDate</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token class-name">Period</span> period <span class="token operator">=</span> <span class="token class-name">Period</span><span class="token punctuation">.</span><span class="token function">between</span><span class="token punctuation">(</span>localDate_1<span class="token punctuation">,</span> localDate_2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>period<span class="token punctuation">.</span><span class="token function">getYears</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>      <span class="token comment">// 运行结果：1</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>period<span class="token punctuation">.</span><span class="token function">getMonths</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment">// 运行结果：1</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>period<span class="token punctuation">.</span><span class="token function">getDays</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>       <span class="token comment">// 运行结果：18</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><h3 id="日期的操纵"><a href="#日期的操纵" class="header-anchor">#</a> 日期的操纵</h3> <p>TemporalAdjuster : 时间校正器。有时我们可能需要获取例如：将日期调整到“下个周日”等操作。</p> <p>TemporalAdjusters : 该类通过静态方法提供了大量的常用 TemporalAdjuster 的实现。</p> <p>例如获取下个周日，如下所示：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">LocalDate</span> nextSunday <span class="token operator">=</span> <span class="token class-name">LocalDate</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token keyword">with</span><span class="token punctuation">(</span><span class="token class-name">TemporalAdjusters</span><span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token class-name">DayOfWeek</span><span class="token punctuation">.</span>SUNDAY<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>完整的示例代码如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">LocalDateTime</span> localDateTime1 <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime1<span class="token punctuation">)</span><span class="token punctuation">;</span>     <span class="token comment">// 2019-10-27T14:19:56.884</span>

<span class="token comment">// 获取这个第一天的日期</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime1<span class="token punctuation">.</span><span class="token keyword">with</span><span class="token punctuation">(</span><span class="token class-name">TemporalAdjusters</span><span class="token punctuation">.</span><span class="token function">firstDayOfMonth</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>            <span class="token comment">// 2019-10-01T14:22:58.574</span>
<span class="token comment">// 获取下个周末的日期</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime1<span class="token punctuation">.</span><span class="token keyword">with</span><span class="token punctuation">(</span><span class="token class-name">TemporalAdjusters</span><span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token class-name">DayOfWeek</span><span class="token punctuation">.</span>SUNDAY<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>       <span class="token comment">// 2019-11-03T14:22:58.574</span>

<span class="token comment">// 自定义：下一个工作日</span>
<span class="token class-name">LocalDateTime</span> localDateTime2 <span class="token operator">=</span> localDateTime1<span class="token punctuation">.</span><span class="token keyword">with</span><span class="token punctuation">(</span>l <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
    <span class="token class-name">LocalDateTime</span> localDateTime <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">LocalDateTime</span><span class="token punctuation">)</span> l<span class="token punctuation">;</span>
    <span class="token class-name">DayOfWeek</span> dayOfWeek <span class="token operator">=</span>  localDateTime<span class="token punctuation">.</span><span class="token function">getDayOfWeek</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">if</span> <span class="token punctuation">(</span>dayOfWeek<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">DayOfWeek</span><span class="token punctuation">.</span>FRIDAY<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
       <span class="token keyword">return</span> localDateTime<span class="token punctuation">.</span><span class="token function">plusDays</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>dayOfWeek<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">DayOfWeek</span><span class="token punctuation">.</span>SATURDAY<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
       <span class="token keyword">return</span> localDateTime<span class="token punctuation">.</span><span class="token function">plusDays</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
       <span class="token keyword">return</span> localDateTime<span class="token punctuation">.</span><span class="token function">plusDays</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：2019-10-28T14:30:17.400</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br></div></div><h3 id="解析与格式化"><a href="#解析与格式化" class="header-anchor">#</a> 解析与格式化</h3> <p>java.time.format.DateTimeFormatter 类：该类提供了三种格式化方法：</p> <ul><li><p>预定义的标准格式</p></li> <li><p>语言环境相关的格式</p></li> <li><p>自定义的格式</p></li></ul> <p>示例代码如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">DateTimeFormatter</span> dateTimeFormatter1 <span class="token operator">=</span> <span class="token class-name">DateTimeFormatter</span><span class="token punctuation">.</span>ISO_DATE<span class="token punctuation">;</span>
<span class="token class-name">LocalDateTime</span> localDateTime <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> strDate1 <span class="token operator">=</span> localDateTime<span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span>dateTimeFormatter1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>strDate1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：2019-10-27</span>

<span class="token comment">// Date -&gt; String</span>
<span class="token class-name">DateTimeFormatter</span> dateTimeFormatter2 <span class="token operator">=</span> <span class="token class-name">DateTimeFormatter</span><span class="token punctuation">.</span><span class="token function">ofPattern</span><span class="token punctuation">(</span><span class="token string">&quot;yyyy-MM-dd  HH:mm:ss&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> strDate2 <span class="token operator">=</span> dateTimeFormatter2<span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span>localDateTime<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>strDate2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：2019-10-27  14:36:11</span>

<span class="token comment">// String -&gt; Date</span>
<span class="token class-name">LocalDateTime</span> localDateTime1 <span class="token operator">=</span> localDateTime<span class="token punctuation">.</span><span class="token function">parse</span><span class="token punctuation">(</span>strDate2<span class="token punctuation">,</span> dateTimeFormatter2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 运行结果：2019-10-27T14:37:39</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br></div></div><h3 id="时区的处理"><a href="#时区的处理" class="header-anchor">#</a> 时区的处理</h3> <p>Java8 中加入了对时区的支持，带时区的时间为分别为：ZonedDate、 ZonedTime、 ZonedDateTime。</p> <p>其中每个时区都对应着 ID，地区ID都为 “{区域}/{城市}”的格式，例如 ： Asia/Shanghai 等。</p> <ul><li><p>ZoneId：该类中包含了所有的时区信息</p></li> <li><p>getAvailableZoneIds() : 可以获取所有时区时区信息</p></li> <li><p>of(id) : 用指定的时区信息获取 ZoneId 对象</p></li></ul> <p>示例代码如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">// 获取所有的时区</span>
<span class="token class-name">Set</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> set <span class="token operator">=</span> <span class="token class-name">ZoneId</span><span class="token punctuation">.</span><span class="token function">getAvailableZoneIds</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>set<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// [Asia/Aden, America/Cuiaba, Etc/GMT+9, Etc/GMT+8, Africa/Nairobi, America/Marigot, Asia/Aqtau, Pacific/Kwajalein, America/El_Salvador, Asia/Pontianak, Africa/Cairo, Pacific/Pago_Pago, Africa/Mbabane, Asia/Kuching, Pacific/Honolulu, Pacific/Rarotonga, America/Guatemala, Australia/Hobart, Europe/London, America/Belize, America/Panama, Asia/Chungking, America/Managua, America/Indiana/Petersburg, Asia/Yerevan, Europe/Brussels, GMT, Europe/Warsaw, America/Chicago, Asia/Kashgar, Chile/Continental, Pacific/Yap, CET, Etc/GMT-1, Etc/GMT-0, Europe/Jersey, America/Tegucigalpa, Etc/GMT-5, Europe/Istanbul, America/Eirunepe, Etc/GMT-4, America/Miquelon, Etc/GMT-3, Europe/Luxembourg, Etc/GMT-2, Etc/GMT-9, America/Argentina/Catamarca, Etc/GMT-8, Etc/GMT-7, Etc/GMT-6, Europe/Zaporozhye, Canada/Yukon, Canada/Atlantic, Atlantic/St_Helena, Australia/Tasmania, Libya, Europe/Guernsey, America/Grand_Turk, US/Pacific-New, Asia/Samarkand, America/Argentina/Cordoba, Asia/Phnom_Penh, Africa/Kigali, Asia/Almaty, US/Alaska, Asia/Dubai, Europe/Isle_of_Man, America/Araguaina, Cuba, Asia/Novosibirsk, America/Argentina/Salta, Etc/GMT+3, Africa/Tunis, Etc/GMT+2, Etc/GMT+1, Pacific/Fakaofo, Africa/Tripoli, Etc/GMT+0, Israel, Africa/Banjul, Etc/GMT+7, Indian/Comoro, Etc/GMT+6, Etc/GMT+5, Etc/GMT+4, Pacific/Port_Moresby, US/Arizona, Antarctica/Syowa, Indian/Reunion, Pacific/Palau, Europe/Kaliningrad, America/Montevideo, Africa/Windhoek, Asia/Karachi, Africa/Mogadishu, Australia/Perth, Brazil/East, Etc/GMT, Asia/Chita, Pacific/Easter, Antarctica/Davis, Antarctica/McMurdo, Asia/Macao, America/Manaus, Africa/Freetown, Europe/Bucharest, Asia/Tomsk, America/Argentina/Mendoza, Asia/Macau, Europe/Malta, Mexico/BajaSur, Pacific/Tahiti, Africa/Asmera, Europe/Busingen, America/Argentina/Rio_Gallegos, Africa/Malabo, Europe/Skopje, America/Catamarca, America/Godthab, Europe/Sarajevo, Australia/ACT, GB-Eire, Africa/Lagos, America/Cordoba, Europe/Rome, Asia/Dacca, Indian/Mauritius, Pacific/Samoa, America/Regina, America/Fort_Wayne, America/Dawson_Creek, Africa/Algiers, Europe/Mariehamn, America/St_Johns, America/St_Thomas, Europe/Zurich, America/Anguilla, Asia/Dili, America/Denver, Africa/Bamako, Europe/Saratov, GB, Mexico/General, Pacific/Wallis, Europe/Gibraltar, Africa/Conakry, Africa/Lubumbashi, Asia/Istanbul, America/Havana, NZ-CHAT, Asia/Choibalsan, America/Porto_Acre, Asia/Omsk, Europe/Vaduz, US/Michigan, Asia/Dhaka, America/Barbados, Europe/Tiraspol, Atlantic/Cape_Verde, Asia/Yekaterinburg, America/Louisville, Pacific/Johnston, Pacific/Chatham, Europe/Ljubljana, America/Sao_Paulo, Asia/Jayapura, America/Curacao, Asia/Dushanbe, America/Guyana, America/Guayaquil, America/Martinique, Portugal, Europe/Berlin, Europe/Moscow, Europe/Chisinau, America/Puerto_Rico, America/Rankin_Inlet, Pacific/Ponape, Europe/Stockholm, Europe/Budapest, America/Argentina/Jujuy, Australia/Eucla, Asia/Shanghai, Universal, Europe/Zagreb, America/Port_of_Spain, Europe/Helsinki, Asia/Beirut, Asia/Tel_Aviv, Pacific/Bougainville, US/Central, Africa/Sao_Tome, Indian/Chagos, America/Cayenne, Asia/Yakutsk, Pacific/Galapagos, Australia/North, Europe/Paris, Africa/Ndjamena, Pacific/Fiji, America/Rainy_River, Indian/Maldives, Australia/Yancowinna, SystemV/AST4, Asia/Oral, America/Yellowknife, Pacific/Enderbury, America/Juneau, Australia/Victoria, America/Indiana/Vevay, Asia/Tashkent, Asia/Jakarta, Africa/Ceuta, Asia/Barnaul, America/Recife, America/Buenos_Aires, America/Noronha, America/Swift_Current, Australia/Adelaide, America/Metlakatla, Africa/Djibouti, America/Paramaribo, Europe/Simferopol, Europe/Sofia, Africa/Nouakchott, Europe/Prague, America/Indiana/Vincennes, Antarctica/Mawson, America/Kralendijk, Antarctica/Troll, Europe/Samara, Indian/Christmas, America/Antigua, Pacific/Gambier, America/Indianapolis, America/Inuvik, America/Iqaluit, Pacific/Funafuti, UTC, Antarctica/Macquarie, Canada/Pacific, America/Moncton, Africa/Gaborone, Pacific/Chuuk, Asia/Pyongyang, America/St_Vincent, Asia/Gaza, Etc/Universal, PST8PDT, Atlantic/Faeroe, Asia/Qyzylorda, Canada/Newfoundland, America/Kentucky/Louisville, America/Yakutat, Asia/Ho_Chi_Minh, Antarctica/Casey, Europe/Copenhagen, Africa/Asmara, Atlantic/Azores, Europe/Vienna, ROK, Pacific/Pitcairn, America/Mazatlan, Australia/Queensland, Pacific/Nauru, Europe/Tirane, Asia/Kolkata, SystemV/MST7, Australia/Canberra, MET, Australia/Broken_Hill, Europe/Riga, America/Dominica, Africa/Abidjan, America/Mendoza, America/Santarem, Kwajalein, America/Asuncion, Asia/Ulan_Bator, NZ, America/Boise, Australia/Currie, EST5EDT, Pacific/Guam, Pacific/Wake, Atlantic/Bermuda, America/Costa_Rica, America/Dawson, Asia/Chongqing, Eire, Europe/Amsterdam, America/Indiana/Knox, America/North_Dakota/Beulah, Africa/Accra, Atlantic/Faroe, Mexico/BajaNorte, America/Maceio, Etc/UCT, Pacific/Apia, GMT0, America/Atka, Pacific/Niue, Australia/Lord_Howe, Europe/Dublin, Pacific/Truk, MST7MDT, America/Monterrey, America/Nassau, America/Jamaica, Asia/Bishkek, America/Atikokan, Atlantic/Stanley, Australia/NSW, US/Hawaii, SystemV/CST6, Indian/Mahe, Asia/Aqtobe, America/Sitka, Asia/Vladivostok, Africa/Libreville, Africa/Maputo, Zulu, America/Kentucky/Monticello, Africa/El_Aaiun, Africa/Ouagadougou, America/Coral_Harbour, Pacific/Marquesas, Brazil/West, America/Aruba, America/North_Dakota/Center, America/Cayman, Asia/Ulaanbaatar, Asia/Baghdad, Europe/San_Marino, America/Indiana/Tell_City, America/Tijuana, Pacific/Saipan, SystemV/YST9, Africa/Douala, America/Chihuahua, America/Ojinaga, Asia/Hovd, America/Anchorage, Chile/EasterIsland, America/Halifax, Antarctica/Rothera, America/Indiana/Indianapolis, US/Mountain, Asia/Damascus, America/Argentina/San_Luis, America/Santiago, Asia/Baku, America/Argentina/Ushuaia, Atlantic/Reykjavik, Africa/Brazzaville, Africa/Porto-Novo, America/La_Paz, Antarctica/DumontDUrville, Asia/Taipei, Antarctica/South_Pole, Asia/Manila, Asia/Bangkok, Africa/Dar_es_Salaam, Poland, Atlantic/Madeira, Antarctica/Palmer, America/Thunder_Bay, Africa/Addis_Ababa, Asia/Yangon, Europe/Uzhgorod, Brazil/DeNoronha, Asia/Ashkhabad, Etc/Zulu, America/Indiana/Marengo, America/Creston, America/Punta_Arenas, America/Mexico_City, Antarctica/Vostok, Asia/Jerusalem, Europe/Andorra, US/Samoa, PRC, Asia/Vientiane, Pacific/Kiritimati, America/Matamoros, America/Blanc-Sablon, Asia/Riyadh, Iceland, Pacific/Pohnpei, Asia/Ujung_Pandang, Atlantic/South_Georgia, Europe/Lisbon, Asia/Harbin, Europe/Oslo, Asia/Novokuznetsk, CST6CDT, Atlantic/Canary, America/Knox_IN, Asia/Kuwait, SystemV/HST10, Pacific/Efate, Africa/Lome, America/Bogota, America/Menominee, America/Adak, Pacific/Norfolk, Europe/Kirov, America/Resolute, Pacific/Tarawa, Africa/Kampala, Asia/Krasnoyarsk, Greenwich, SystemV/EST5, America/Edmonton, Europe/Podgorica, Australia/South, Canada/Central, Africa/Bujumbura, America/Santo_Domingo, US/Eastern, Europe/Minsk, Pacific/Auckland, Africa/Casablanca, America/Glace_Bay, Canada/Eastern, Asia/Qatar, Europe/Kiev, Singapore, Asia/Magadan, SystemV/PST8, America/Port-au-Prince, Europe/Belfast, America/St_Barthelemy, Asia/Ashgabat, Africa/Luanda, America/Nipigon, Atlantic/Jan_Mayen, Brazil/Acre, Asia/Muscat, Asia/Bahrain, Europe/Vilnius, America/Fortaleza, Etc/GMT0, US/East-Indiana, America/Hermosillo, America/Cancun, Africa/Maseru, Pacific/Kosrae, Africa/Kinshasa, Asia/Kathmandu, Asia/Seoul, Australia/Sydney, America/Lima, Australia/LHI, America/St_Lucia, Europe/Madrid, America/Bahia_Banderas, America/Montserrat, Asia/Brunei, America/Santa_Isabel, Canada/Mountain, America/Cambridge_Bay, Asia/Colombo, Australia/West, Indian/Antananarivo, Australia/Brisbane, Indian/Mayotte, US/Indiana-Starke, Asia/Urumqi, US/Aleutian, Europe/Volgograd, America/Lower_Princes, America/Vancouver, Africa/Blantyre, America/Rio_Branco, America/Danmarkshavn, America/Detroit, America/Thule, Africa/Lusaka, Asia/Hong_Kong, Iran, America/Argentina/La_Rioja, Africa/Dakar, SystemV/CST6CDT, America/Tortola, America/Porto_Velho, Asia/Sakhalin, Etc/GMT+10, America/Scoresbysund, Asia/Kamchatka, Asia/Thimbu, Africa/Harare, Etc/GMT+12, Etc/GMT+11, Navajo, America/Nome, Europe/Tallinn, Turkey, Africa/Khartoum, Africa/Johannesburg, Africa/Bangui, Europe/Belgrade, Jamaica, Africa/Bissau, Asia/Tehran, WET, Europe/Astrakhan, Africa/Juba, America/Campo_Grande, America/Belem, Etc/Greenwich, Asia/Saigon, America/Ensenada, Pacific/Midway, America/Jujuy, Africa/Timbuktu, America/Bahia, America/Goose_Bay, America/Virgin, America/Pangnirtung, Asia/Katmandu, America/Phoenix, Africa/Niamey, America/Whitehorse, Pacific/Noumea, Asia/Tbilisi, America/Montreal, Asia/Makassar, America/Argentina/San_Juan, Hongkong, UCT, Asia/Nicosia, America/Indiana/Winamac, SystemV/MST7MDT, America/Argentina/ComodRivadavia, America/Boa_Vista, America/Grenada, Asia/Atyrau, Australia/Darwin, Asia/Khandyga, Asia/Kuala_Lumpur, Asia/Famagusta, Asia/Thimphu, Asia/Rangoon, Europe/Bratislava, Asia/Calcutta, America/Argentina/Tucuman, Asia/Kabul, Indian/Cocos, Japan, Pacific/Tongatapu, America/New_York, Etc/GMT-12, Etc/GMT-11, Etc/GMT-10, SystemV/YST9YDT, Europe/Ulyanovsk, Etc/GMT-14, Etc/GMT-13, W-SU, America/Merida, EET, America/Rosario, Canada/Saskatchewan, America/St_Kitts, Arctic/Longyearbyen, America/Fort_Nelson, America/Caracas, America/Guadeloupe, Asia/Hebron, Indian/Kerguelen, SystemV/PST8PDT, Africa/Monrovia, Asia/Ust-Nera, Egypt, Asia/Srednekolymsk, America/North_Dakota/New_Salem, Asia/Anadyr, Australia/Melbourne, Asia/Irkutsk, America/Shiprock, America/Winnipeg, Europe/Vatican, Asia/Amman, Etc/UTC, SystemV/AST4ADT, Asia/Tokyo, America/Toronto, Asia/Singapore, Australia/Lindeman, America/Los_Angeles, SystemV/EST5EDT, Pacific/Majuro, America/Argentina/Buenos_Aires, Europe/Nicosia, Pacific/Guadalcanal, Europe/Athens, US/Pacific, Europe/Monaco]</span>

<span class="token comment">// 通过时区构建LocalDateTime</span>
<span class="token class-name">LocalDateTime</span> localDateTime1 <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token class-name">ZoneId</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token string">&quot;America/El_Salvador&quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 2019-10-27T00:46:21.268</span>

<span class="token comment">// 以时区格式显示时间</span>
<span class="token class-name">LocalDateTime</span> localDateTime2 <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">ZonedDateTime</span> zonedDateTime1 <span class="token operator">=</span> localDateTime2<span class="token punctuation">.</span><span class="token function">atZone</span><span class="token punctuation">(</span><span class="token class-name">ZoneId</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token string">&quot;Africa/Nairobi&quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>zonedDateTime1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 2019-10-27T14:46:21.273+03:00[Africa/Nairobi]</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><h3 id="与传统日期处理的转换"><a href="#与传统日期处理的转换" class="header-anchor">#</a> 与传统日期处理的转换</h3> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20210314195305164.jpg" loading="lazy" class="lazy"></p> <h2 id="jdk注解"><a href="#jdk注解" class="header-anchor">#</a> JDK注解</h2> <h3 id="jdk5中的注解"><a href="#jdk5中的注解" class="header-anchor">#</a> JDK5中的注解</h3> <p><strong>1.注解（@）</strong></p> <p>注解就相当于一种标记，在程序中加了注解就等于为程序加了某种标记。（JDK1.5新特性）。</p> <p><strong>2.作用</strong></p> <p>告诉javac编译器或者java开发工具……向其传递某种信息，作为一个标记。</p> <p><strong>3.如何理解注解？</strong></p> <p>一个注解就是一个类。</p> <p>标记可以加在包、类、字段、方法，方法参数以及局部变量上。可以同时存在多个注解。</p> <p>每一个注解结尾都没有“；”或者其他特别符号。</p> <p>定义注解需要的基础注解信息如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@SuppressWarnings</span><span class="token punctuation">(</span><span class="token string">&quot;deprecation&quot;</span><span class="token punctuation">)</span>  <span class="token comment">//编译器警告过时（source阶段）</span>
<span class="token annotation punctuation">@Deprecated</span>						<span class="token comment">//过时（Runtime阶段）</span>
<span class="token annotation punctuation">@Override</span>						<span class="token comment">//重写（source阶段）</span>
<span class="token annotation punctuation">@Retention</span><span class="token punctuation">(</span><span class="token class-name">RetentionPolicy</span><span class="token punctuation">.</span>RUNTIME<span class="token punctuation">)</span>	
<span class="token comment">//保留注解到程序运行时。（Runtime阶段）</span>
<span class="token annotation punctuation">@Target</span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>METHOD<span class="token punctuation">,</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>TYPE<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token comment">//标记既能定义在方法上，又能定义在类、接口、枚举上等。</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p><strong>注意：</strong></p> <p>1）添加注解需要有注解类。RetentionPolicy是一个枚举类（有三个成员）。</p> <p>2）Target中可以存放数组。它的默认值为任何元素。</p> <ul><li><p>ElementType.METHOD：表示只能标记在方法上。</p></li> <li><p>ElementType.TYPE：表示只能标记定义在类上、接口上、枚举上等</p> <p>3）ElementType也是枚举类。成员包括：ANNOTATION_TYPE（注解）、CONSTRUCTOR（构造方法）、FIEID（成员变量）、LOCAL_VARIABLE（变量）、METHOD（方法）、PACKAGE（包）、PARAMETER（参数）、TYPE。</p></li></ul> <p><strong>4.关于注解</strong></p> <ul><li><p>元注解：注解的注解（理解：给一个注解类再加注解）</p></li> <li><p>元数据：数据的数据</p></li> <li><p>元信息：信息的信息</p></li></ul> <p><strong>5.注解分为三个阶段</strong></p> <p>java源文件--&gt; class文件 --&gt; 内存中的字节码。</p> <p>Retention的注解有三种取值：(分别对应注解的三个阶段)</p> <ul><li><p>RetentionPolicy.SOURCE</p></li> <li><p>RetentionPolicy.CLASS</p></li> <li><p>RetentionPolicy.RUNTIME</p></li></ul> <p>注意：注解的默认阶段是Class。</p> <p><strong>6.注解的属性类型</strong></p> <p>原始类型（就是八个基本数据类型）、String类型、Class类型、数组类型、枚举类型、注解类型。</p> <p><strong>7.为注解增加属性</strong></p> <p>value：是一个特殊的属性，若在设置值时只有一个value属性需要设置或者其他属性都采用默认值时 ，那么value=可以省略，直接写所设置的值即可。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>例如：<span class="token annotation punctuation">@SuppressWarnings</span><span class="token punctuation">(</span><span class="token string">&quot;deprecation&quot;</span><span class="token punctuation">)</span>

为属性指定缺省值（默认值）：
例如：<span class="token class-name">String</span> <span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token string">&quot;blue&quot;</span><span class="token punctuation">;</span> <span class="token comment">//定义在注解类中</span>

数组类型的属性<span class="token operator">:</span>
例如：<span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">arrayArr</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">default</span> <span class="token punctuation">{</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">}</span><span class="token punctuation">;</span><span class="token comment">//定义在注解类中</span>
<span class="token class-name">SunAnnotation</span><span class="token punctuation">(</span>arrayArr<span class="token operator">=</span><span class="token punctuation">{</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">9</span><span class="token punctuation">,</span><span class="token number">8</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token comment">//设置数组值</span>
注意<span class="token operator">:</span>如果数组属性中只有一个元素时，属性值部分可以省略大括号。
例如：<span class="token class-name">SunAnnotation</span><span class="token punctuation">(</span>arrayArr<span class="token operator">=</span><span class="token number">9</span><span class="token punctuation">)</span>

枚举类型的属性：
例如：<span class="token class-name">EnumDemo<span class="token punctuation">.</span>TrafficLamp</span> <span class="token function">lamp</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment">////枚举类型属性, 定义在注解类中，这里使用了自定义的枚举类EnumDemo.java并没有给出相关代码，这里只是举个例子</span>
<span class="token keyword">default</span> <span class="token class-name">EnumDemo<span class="token punctuation">.</span>TrafficLamp</span><span class="token punctuation">.</span>RED<span class="token punctuation">;</span>

注解类型的属性：
例如：<span class="token class-name">MetaAnnotation</span> <span class="token function">annotationAttr</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment">//定义在一个注解类中,并指定缺省值，</span>
<span class="token comment">//此属性关联到注解类：MetaAnnotation.java, </span>
<span class="token keyword">default</span> <span class="token annotation punctuation">@MetaAnnotation</span><span class="token punctuation">(</span><span class="token string">&quot;lhm&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//设置注解属性值</span>
<span class="token annotation punctuation">@SunAnnotation</span><span class="token punctuation">(</span>annotationAttr<span class="token operator">=</span><span class="token annotation punctuation">@MetaAnnotation</span><span class="token punctuation">(</span><span class="token string">&quot;flx&quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br></div></div><h3 id="java8中的注解"><a href="#java8中的注解" class="header-anchor">#</a> Java8中的注解</h3> <p>对于注解（也被称做元数据），Java 8 主要有两点改进：类型注解和重复注解。</p> <p><strong>1.类型注解</strong></p> <p>1）Java 8 的类型注解扩展了注解使用的范围。</p> <p>在java 8之前，注解只能是在声明的地方所使用，java8开始，注解可以应用在任何地方。</p> <p>例如：</p> <p>创建类实例</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">new</span> <span class="token annotation punctuation">@Interned</span> <span class="token class-name">MyObject</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>类型映射</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>myString <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token annotation punctuation">@NonNull</span> <span class="token class-name">String</span><span class="token punctuation">)</span> str<span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>implements 语句中</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">class</span> <span class="token class-name">UnmodifiableList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token keyword">implements</span><span class="token annotation punctuation">@Readonly</span> <span class="token class-name">List</span><span class="token operator">&lt;</span><span class="token annotation punctuation">@Readonly</span> <span class="token class-name">T</span><span class="token operator">&gt;</span> <span class="token punctuation">{</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>throw exception声明</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">void</span> <span class="token function">monitorTemperature</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span><span class="token annotation punctuation">@Critical</span> <span class="token class-name">TemperatureException</span> <span class="token punctuation">{</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>注意：</p> <p>在Java 8里面，当类型转化甚至分配新对象的时候，都可以在声明变量或者参数的时候使用注解。
Java注解可以支持任意类型。</p> <p>类型注解只是语法而不是语义，并不会影响java的编译时间，加载时间，以及运行时间，也就是说，编译成class文件的时候并不包含类型注解。</p> <p>2）新增ElementType.TYPE_USE 和ElementType.TYPE_PARAMETER（在Target上）</p> <p>新增的两个注释的程序元素类型 ElementType.TYPE_USE 和 ElementType.TYPE_PARAMETER用来描述注解的新场合。</p> <ul><li><p>ElementType.TYPE_PARAMETER 表示该注解能写在类型变量的声明语句中。</p></li> <li><p>ElementType.TYPE_USE 表示该注解能写在使用类型的任何语句中（例如：声明语句、泛型和强制转换语句中的类型）。</p></li></ul> <p>例如，下面的示例。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Target</span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>TYPE_PARAMETER<span class="token punctuation">,</span> <span class="token class-name">ElementType</span><span class="token punctuation">.</span>TYPE_USE<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@interface</span> <span class="token class-name">MyAnnotation</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>3)类型注解的作用</p> <p>类型注解被用来支持在Java的程序中做强类型检查。配合第三方插件工具Checker Framework（注：此插件so easy,这里不介绍了），可以在编译的时候检测出runtime error（例如：UnsupportedOperationException； NumberFormatException；NullPointerException异常等都是runtime error），以提高代码质量。这就是类型注解的作用。</p> <p>注意：使用Checker Framework可以找到类型注解出现的地方并检查。</p> <p>例如下面的代码。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">import</span> <span class="token import"><span class="token namespace">checkers<span class="token punctuation">.</span>nullness<span class="token punctuation">.</span>quals<span class="token punctuation">.</span></span><span class="token operator">*</span></span><span class="token punctuation">;</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TestDemo</span><span class="token punctuation">{</span>
    <span class="token keyword">void</span> <span class="token function">sample</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token annotation punctuation">@NonNull</span> <span class="token class-name">Object</span> my <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>使用javac编译上面的类：（当然若下载了Checker Framework插件就不需要这么麻烦了）</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>javac <span class="token operator">-</span>processor <span class="token class-name"><span class="token namespace">checkers<span class="token punctuation">.</span>nullness<span class="token punctuation">.</span></span>NullnessChecker</span> <span class="token class-name">TestDemo</span><span class="token punctuation">.</span>java
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>上面编译是通过的，但若修改代码：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@NonNull</span> <span class="token class-name">Object</span> my <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>但若不想使用类型注解检测出来错误，则不需要processor，正常javac TestDemo.java是可以通过编译的，但是运行时会报 NullPointerException 异常。</p> <p>为了能在编译期间就自动检查出这类异常，可以通过类型注解结合 Checker Framework 提前排查出来错误异常。</p> <p>注意java 5,6,7版本是不支持注解@NonNull，但checker framework 有个向下兼容的解决方案，就是将类型注解@NonNull 用/**/注释起来。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">import</span> <span class="token import"><span class="token namespace">checkers<span class="token punctuation">.</span>nullness<span class="token punctuation">.</span>quals<span class="token punctuation">.</span></span><span class="token operator">*</span></span><span class="token punctuation">;</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TestDemo</span><span class="token punctuation">{</span>
    <span class="token keyword">void</span> <span class="token function">sample</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">/*@NonNull*/</span> <span class="token class-name">Object</span> my <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>这样javac编译器就会忽略掉注释块，但用checker framework里面的javac编译器同样能够检测出@NonNull错误。
通过 类型注解 + checker framework 可以在编译时就找到runtime error。</p> <p><strong>2.重复注解</strong></p> <p>允许在同一声明类型（类，属性，或方法）上多次使用同一个注解。</p> <p>Java8以前的版本使用注解有一个限制是相同的注解在同一位置只能使用一次，不能使用多次。</p> <p>Java 8 引入了重复注解机制，这样相同的注解可以在同一地方使用多次。重复注解机制本身必须用 @Repeatable 注解。</p> <p>实际上，重复注解不是一个语言上的改变，只是编译器层面的改动，技术层面仍然是一样的。</p> <p>例如，我们可以使用如下示例来具体对比Java8之前的版本和Java8中的注解。</p> <p><strong>1）</strong> 自定义一个包装类Hints注解用来放置一组具体的Hint注解</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@interface</span> <span class="token class-name">MyHints</span> <span class="token punctuation">{</span>
    <span class="token class-name">Hint</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
 
<span class="token annotation punctuation">@Repeatable</span><span class="token punctuation">(</span><span class="token class-name">MyHints</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@interface</span> <span class="token class-name">Hint</span> <span class="token punctuation">{</span>
    <span class="token class-name">String</span> <span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>使用包装类当容器来存多个注解（旧版本方法）</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@MyHints</span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token annotation punctuation">@Hint</span><span class="token punctuation">(</span><span class="token string">&quot;hint1&quot;</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token annotation punctuation">@Hint</span><span class="token punctuation">(</span><span class="token string">&quot;hint2&quot;</span><span class="token punctuation">)</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">Person</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>使用多重注解（新方法）</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Hint</span><span class="token punctuation">(</span><span class="token string">&quot;hint1&quot;</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@Hint</span><span class="token punctuation">(</span><span class="token string">&quot;hint2&quot;</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">Person</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p><strong>2)</strong> 完整类测试如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">RepeatingAnnotations</span> <span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Target</span><span class="token punctuation">(</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>TYPE<span class="token punctuation">)</span>
    <span class="token annotation punctuation">@Retention</span><span class="token punctuation">(</span><span class="token class-name">RetentionPolicy</span><span class="token punctuation">.</span>RUNTIME<span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token annotation punctuation">@interface</span> <span class="token class-name">Filters</span> <span class="token punctuation">{</span>
        <span class="token class-name">Filter</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    
    <span class="token annotation punctuation">@Target</span><span class="token punctuation">(</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>TYPE<span class="token punctuation">)</span>
    <span class="token annotation punctuation">@Retention</span><span class="token punctuation">(</span><span class="token class-name">RetentionPolicy</span><span class="token punctuation">.</span>RUNTIME<span class="token punctuation">)</span>
    <span class="token annotation punctuation">@Repeatable</span><span class="token punctuation">(</span><span class="token class-name">Filters</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token annotation punctuation">@interface</span> <span class="token class-name">Filter</span> <span class="token punctuation">{</span>
        <span class="token class-name">String</span> <span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token annotation punctuation">@Filter</span><span class="token punctuation">(</span><span class="token string">&quot;filter1&quot;</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@Filter</span><span class="token punctuation">(</span><span class="token string">&quot;filter2&quot;</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">Filterable</span> <span class="token punctuation">{</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Filter</span> filter <span class="token operator">:</span> <span class="token class-name">Filterable</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">getAnnotationsByType</span><span class="token punctuation">(</span><span class="token class-name">Filter</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>filter<span class="token punctuation">.</span><span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br></div></div><p>输出结果：</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>filter1
filter2
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>分析：</strong></p> <p>注释Filter被@Repeatable( Filters.class )注释。Filters 只是一个容器，它持有Filter, 编译器尽力向程序员隐藏它的存在。通过这样的方式，Filterable接口可以被Filter注释两次。</p> <p>另外，反射的API提供一个新方法getAnnotationsByType() 来返回重复注释的类型（注意Filterable.class.getAnnotation( Filters.class )将会返回编译器注入的Filters实例。</p> <p><strong>3）</strong> java 8之前也有重复使用注解的解决方案，但可读性不好。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token annotation punctuation">@interface</span> <span class="token class-name">MyAnnotation</span> <span class="token punctuation">{</span>  
     <span class="token class-name">String</span> <span class="token function">role</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token punctuation">}</span>  
 
<span class="token keyword">public</span> <span class="token annotation punctuation">@interface</span> <span class="token class-name">Annotations</span> <span class="token punctuation">{</span>  
    <span class="token class-name">MyAnnotation</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token punctuation">}</span>  
 
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">RepeatAnnotationUseOldVersion</span> <span class="token punctuation">{</span>  
    <span class="token annotation punctuation">@Annotations</span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token annotation punctuation">@MyAnnotation</span><span class="token punctuation">(</span>role<span class="token operator">=</span><span class="token string">&quot;Admin&quot;</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token annotation punctuation">@MyAnnotation</span><span class="token punctuation">(</span>role<span class="token operator">=</span><span class="token string">&quot;Manager&quot;</span><span class="token punctuation">)</span><span class="token punctuation">}</span><span class="token punctuation">)</span>  
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doSomeThing</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>  
    <span class="token punctuation">}</span>  
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br></div></div><p><strong>Java8的实现方式</strong>（由另一个注解来存储重复注解，在使用时候，用存储注解Authorities来扩展重复注解）<strong>，可读性更强。</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token annotation punctuation">@Repeatable</span><span class="token punctuation">(</span><span class="token class-name">Annotations</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span> 
<span class="token keyword">public</span> <span class="token annotation punctuation">@interface</span> <span class="token class-name">MyAnnotation</span> <span class="token punctuation">{</span>  
     <span class="token class-name">String</span> <span class="token function">role</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token punctuation">}</span>  
 
<span class="token keyword">public</span> <span class="token annotation punctuation">@interface</span> <span class="token class-name">Annotations</span> <span class="token punctuation">{</span>  
    <span class="token class-name">MyAnnotation</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token punctuation">}</span>  
 
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">RepeatAnnotationUseOldVersion</span> <span class="token punctuation">{</span>  
	<span class="token annotation punctuation">@MyAnnotation</span><span class="token punctuation">(</span>role<span class="token operator">=</span><span class="token string">&quot;Admin&quot;</span><span class="token punctuation">)</span>  
    <span class="token annotation punctuation">@MyAnnotation</span><span class="token punctuation">(</span>role<span class="token operator">=</span><span class="token string">&quot;Manager&quot;</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doSomeThing</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>  
    <span class="token punctuation">}</span>  
<span class="token punctuation">}</span> 
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><p><strong>什么？没看懂？那就再来一波！！！</strong></p> <h3 id="java8对注解的增强"><a href="#java8对注解的增强" class="header-anchor">#</a> Java8对注解的增强</h3> <p>Java 8对注解处理提供了两点改进：可重复的注解及可用于类型的注解。总体来说，比较简单，下面，我们就以实例的形式来说明Java8中的重复注解和类型注解。</p> <p>首先，我们来定义一个注解类BingheAnnotation，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">package</span> <span class="token namespace">io<span class="token punctuation">.</span>mykit<span class="token punctuation">.</span>binghe<span class="token punctuation">.</span>java8<span class="token punctuation">.</span>annotition</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span></span><span class="token operator">*</span></span><span class="token punctuation">;</span>

<span class="token comment">/**
 * @author binghe
 * @version 1.0.0
 * @description 定义注解
 */</span>
<span class="token annotation punctuation">@Repeatable</span><span class="token punctuation">(</span><span class="token class-name">BingheAnnotations</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@Target</span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>TYPE<span class="token punctuation">,</span> <span class="token class-name">ElementType</span><span class="token punctuation">.</span>FIELD<span class="token punctuation">,</span> <span class="token class-name">ElementType</span><span class="token punctuation">.</span>METHOD<span class="token punctuation">,</span> <span class="token class-name">ElementType</span><span class="token punctuation">.</span>PARAMETER<span class="token punctuation">,</span> <span class="token class-name">ElementType</span><span class="token punctuation">.</span>CONSTRUCTOR<span class="token punctuation">,</span> <span class="token class-name">ElementType</span><span class="token punctuation">.</span>LOCAL_VARIABLE<span class="token punctuation">,</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>TYPE_PARAMETER<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@Retention</span><span class="token punctuation">(</span><span class="token class-name">RetentionPolicy</span><span class="token punctuation">.</span>RUNTIME<span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token annotation punctuation">@interface</span> <span class="token class-name">BingheAnnotation</span> <span class="token punctuation">{</span>
    <span class="token class-name">String</span> <span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><p>注意：在BingheAnnotation注解类上比普通的注解多了一个@Repeatable(BingheAnnotations.class)注解，有小伙伴会问：这个是啥啊？这个就是Java8中定义可重复注解的关键，至于BingheAnnotations.class，大家别急，继续往下看就明白了。</p> <p>接下来，咱们定义一个BingheAnnotations注解类，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">package</span> <span class="token namespace">io<span class="token punctuation">.</span>mykit<span class="token punctuation">.</span>binghe<span class="token punctuation">.</span>java8<span class="token punctuation">.</span>annotation</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span></span><span class="token operator">*</span></span><span class="token punctuation">;</span>

<span class="token comment">/**
 * @author binghe
 * @version 1.0.0
 * @description 定义注解
 */</span>
<span class="token annotation punctuation">@Target</span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>TYPE<span class="token punctuation">,</span> <span class="token class-name">ElementType</span><span class="token punctuation">.</span>FIELD<span class="token punctuation">,</span> <span class="token class-name">ElementType</span><span class="token punctuation">.</span>METHOD<span class="token punctuation">,</span> <span class="token class-name">ElementType</span><span class="token punctuation">.</span>PARAMETER<span class="token punctuation">,</span> <span class="token class-name">ElementType</span><span class="token punctuation">.</span>CONSTRUCTOR<span class="token punctuation">,</span> <span class="token class-name">ElementType</span><span class="token punctuation">.</span>LOCAL_VARIABLE<span class="token punctuation">,</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>TYPE_PARAMETER<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@Retention</span><span class="token punctuation">(</span><span class="token class-name">RetentionPolicy</span><span class="token punctuation">.</span>RUNTIME<span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token annotation punctuation">@interface</span> <span class="token class-name">BingheAnnotations</span> <span class="token punctuation">{</span>
    <span class="token class-name">BingheAnnotation</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br></div></div><p>看到这里，大家明白了吧！！没错，BingheAnnotations也是一个注解类，它相比于BingheAnnotation注解类来说，少了一个@Repeatable(BingheAnnotations.class)注解，也就是说，BingheAnnotations注解类的定义与普通的注解几乎没啥区别。值得注意的是，我们在BingheAnnotations注解类中，定义了一个BingheAnnotation注解类的数组，也就是说，在BingheAnnotations注解类中，包含有多个BingheAnnotation注解。所以，在BingheAnnotation注解类上指定@Repeatable(BingheAnnotations.class)来说明可以在类、字段、方法、参数、构造方法、参数上重复使用BingheAnnotation注解。</p> <p>接下来，我们创建一个Binghe类，在Binghe类中定义一个init()方法，在init方法上，重复使用@BingheAnnotation注解指定相应的数据，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">package</span> <span class="token namespace">io<span class="token punctuation">.</span>mykit<span class="token punctuation">.</span>binghe<span class="token punctuation">.</span>java8<span class="token punctuation">.</span>annotation</span><span class="token punctuation">;</span>

<span class="token comment">/**
 * @author binghe
 * @version 1.0.0
 * @description 测试注解
 */</span>
<span class="token annotation punctuation">@BingheAnnotation</span><span class="token punctuation">(</span><span class="token string">&quot;binghe&quot;</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@BingheAnnotation</span><span class="token punctuation">(</span><span class="token string">&quot;class&quot;</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Binghe</span> <span class="token punctuation">{</span>

    <span class="token annotation punctuation">@BingheAnnotation</span><span class="token punctuation">(</span><span class="token string">&quot;init&quot;</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@BingheAnnotation</span><span class="token punctuation">(</span><span class="token string">&quot;method&quot;</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">init</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>

    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div><p>到此，我们就可以测试重复注解了，创建类BingheAnnotationTest，对重复注解进行测试，如下所示。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">package</span> <span class="token namespace">io<span class="token punctuation">.</span>mykit<span class="token punctuation">.</span>binghe<span class="token punctuation">.</span>java8<span class="token punctuation">.</span>annotation</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span><span class="token class-name">Method</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span></span><span class="token class-name">Arrays</span></span><span class="token punctuation">;</span>

<span class="token comment">/**
 * @author binghe
 * @version 1.0.0
 * @description 测试注解
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">BingheAnnotationTest</span> <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">NoSuchMethodException</span> <span class="token punctuation">{</span>
        <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Binghe</span><span class="token punctuation">&gt;</span></span> clazz <span class="token operator">=</span> <span class="token class-name">Binghe</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">;</span>
        <span class="token class-name">BingheAnnotation</span><span class="token punctuation">[</span><span class="token punctuation">]</span> annotations <span class="token operator">=</span> clazz<span class="token punctuation">.</span><span class="token function">getAnnotationsByType</span><span class="token punctuation">(</span><span class="token class-name">BingheAnnotation</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;类上的重复注解如下：&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span>annotations<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">print</span><span class="token punctuation">(</span>a<span class="token punctuation">.</span><span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot; &quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;=============================&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">Method</span> method <span class="token operator">=</span> clazz<span class="token punctuation">.</span><span class="token function">getMethod</span><span class="token punctuation">(</span><span class="token string">&quot;init&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        annotations <span class="token operator">=</span> method<span class="token punctuation">.</span><span class="token function">getAnnotationsByType</span><span class="token punctuation">(</span><span class="token class-name">BingheAnnotation</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;方法上的重复注解如下：&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span>annotations<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">print</span><span class="token punctuation">(</span>a<span class="token punctuation">.</span><span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot; &quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br></div></div><p>运行main()方法，输出如下的结果信息。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>类上的重复注解如下：
binghe class 
<span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">=</span>
方法上的重复注解如下：
init method 
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><h2 id="写在最后"><a href="#写在最后" class="header-anchor">#</a> 写在最后</h2> <blockquote><p>如果你觉得冰河写的还不错，请微信搜索并关注「 <strong>冰河技术</strong> 」微信公众号，跟冰河学习高并发、分布式、微服务、大数据、互联网和云原生技术，「 <strong>冰河技术</strong> 」微信公众号更新了大量技术专题，每一篇技术文章干货满满！不少读者已经通过阅读「 <strong>冰河技术</strong> 」微信公众号文章，吊打面试官，成功跳槽到大厂；也有不少读者实现了技术上的飞跃，成为公司的技术骨干！如果你也想像他们一样提升自己的能力，实现技术能力的飞跃，进大厂，升职加薪，那就关注「 <strong>冰河技术</strong> 」微信公众号吧，每天更新超硬核技术干货，让你对如何提升技术能力不再迷茫！</p></blockquote> <p><img alt="" data-src="https://img-blog.csdnimg.cn/20200906013715889.png" loading="lazy" class="lazy"></p></div> <footer class="page-edit"><div class="edit-link"><a href="https://github.com/binghe001/BingheGuide/edit/master/docs/md/core/java/java8/2022-04-01-001-Java8新特性总结.md" target="_blank" rel="noopener noreferrer">在 GitHub 上编辑此页</a> <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></div> <div class="last-updated"><span class="prefix">上次更新: </span> <span class="time">2022/5/23</span></div></footer> <div class="page-nav"><p class="inner"><span class="prev">
        ←
        <a href="/md/core/java/java8/2022-03-31-016-重复注解与类型注解，你真的学会了吗.html" class="prev">
          重复注解与类型注解，你真的学会了吗？
        </a></span> <!----></p></div> </main></div> <aside class="page-sidebar"> <div class="page-side-toolbar"><div class="option-box-toc-fixed"><div class="toc-container-sidebar"><div class="pos-box"><div class="icon-arrow"></div> <div class="scroll-box" style="max-height:650px"><div style="font-weight:bold;text-align:center;">Java8新特性总结</div> <hr> <div class="toc-box"><ul class="toc-sidebar-links"><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java8有哪些新特性" class="toc-sidebar-link">Java8有哪些新特性？</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java8有哪些优点" class="toc-sidebar-link">Java8有哪些优点？</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#lambda表达式" class="toc-sidebar-link">Lambda表达式</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#什么是lambda表达式" class="toc-sidebar-link">什么是Lambda表达式？</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#匿名内部类" class="toc-sidebar-link">匿名内部类</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#lambda表达式-2" class="toc-sidebar-link">Lambda表达式</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#对比常规方法和lambda表达式" class="toc-sidebar-link">对比常规方法和Lambda表达式</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#匿名类到lambda表达式" class="toc-sidebar-link">匿名类到Lambda表达式</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#lambda表达式的语法" class="toc-sidebar-link">Lambda表达式的语法</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#函数式接口" class="toc-sidebar-link">函数式接口</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#lambda表达式典型案例" class="toc-sidebar-link">Lambda表达式典型案例</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#案例一" class="toc-sidebar-link">案例一</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#案例二" class="toc-sidebar-link">案例二</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#案例三" class="toc-sidebar-link">案例三</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#函数式接口总览" class="toc-sidebar-link">函数式接口总览</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#四大核心函数式接口总览" class="toc-sidebar-link">四大核心函数式接口总览</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#其他函数接口总览" class="toc-sidebar-link">其他函数接口总览</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#四大核心函数式接口" class="toc-sidebar-link">四大核心函数式接口</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#consumer接口" class="toc-sidebar-link">Consumer接口</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#supplier接口" class="toc-sidebar-link">Supplier接口</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#function接口" class="toc-sidebar-link">Function接口</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#predicate接口" class="toc-sidebar-link">Predicate接口</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java7与java8中的hashmap" class="toc-sidebar-link">Java7与Java8中的HashMap</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#jdk8-hashmap重排序" class="toc-sidebar-link">JDK8 HashMap重排序</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#筛选与切片" class="toc-sidebar-link">筛选与切片</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#中间操作" class="toc-sidebar-link">中间操作</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#终止操作" class="toc-sidebar-link">终止操作</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#归约" class="toc-sidebar-link">归约</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#optional-容器类" class="toc-sidebar-link">Optional 容器类</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#方法引用与构造器引用" class="toc-sidebar-link">方法引用与构造器引用</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#方法引用" class="toc-sidebar-link">方法引用</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#构造器引用" class="toc-sidebar-link">构造器引用</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#数组引用" class="toc-sidebar-link">数组引用</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java8中的stream" class="toc-sidebar-link">Java8中的Stream</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#什么是stream" class="toc-sidebar-link">什么是Stream?</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream操作的三个步骤" class="toc-sidebar-link">Stream操作的三个步骤</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#如何创建stream" class="toc-sidebar-link">如何创建Stream?</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream的中间操作" class="toc-sidebar-link">Stream的中间操作</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream-的终止操作" class="toc-sidebar-link">Stream 的终止操作</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#并行流与串行流" class="toc-sidebar-link">并行流与串行流</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#fork-join-框架" class="toc-sidebar-link">Fork/Join 框架</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream概述" class="toc-sidebar-link">Stream概述</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#何为stream" class="toc-sidebar-link">何为Stream?</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream操作步骤" class="toc-sidebar-link">Stream操作步骤</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#如何创建stream流" class="toc-sidebar-link">如何创建Stream流？</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream的中间操作-2" class="toc-sidebar-link">Stream的中间操作</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#筛选与切片-2" class="toc-sidebar-link">筛选与切片</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#映射" class="toc-sidebar-link">映射</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#排序" class="toc-sidebar-link">排序</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream的终止操作" class="toc-sidebar-link">Stream的终止操作</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#查找与匹配" class="toc-sidebar-link">查找与匹配</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#规约" class="toc-sidebar-link">规约</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#收集" class="toc-sidebar-link">收集</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#如何收集stream流" class="toc-sidebar-link">如何收集Stream流？</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#什么是并行流" class="toc-sidebar-link">什么是并行流？</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#fork-join-框架-2" class="toc-sidebar-link">Fork/Join 框架</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#fork-join-框架与传统线程池有啥区别" class="toc-sidebar-link">Fork/Join 框架与传统线程池有啥区别？</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#fork-join框架实例" class="toc-sidebar-link">Fork/Join框架实例</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java8中的并行流实例" class="toc-sidebar-link">Java8中的并行流实例</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#optional类" class="toc-sidebar-link">Optional类</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#什么是optional类" class="toc-sidebar-link">什么是Optional类？</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#optional类示例" class="toc-sidebar-link">Optional类示例</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#默认方法" class="toc-sidebar-link">默认方法</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#接口中的默认方法" class="toc-sidebar-link">接口中的默认方法</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#默认方法的原则" class="toc-sidebar-link">默认方法的原则</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#接口中的静态方法" class="toc-sidebar-link">接口中的静态方法</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#本地时间和时间戳" class="toc-sidebar-link">本地时间和时间戳</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#使用-localdate、-localtime、-localdatetime" class="toc-sidebar-link">使用 LocalDate、 LocalTime、 LocalDateTime</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#instant-时间戳" class="toc-sidebar-link">Instant 时间戳</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#duration-和-period" class="toc-sidebar-link">Duration 和 Period</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#日期的操纵" class="toc-sidebar-link">日期的操纵</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#解析与格式化" class="toc-sidebar-link">解析与格式化</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#时区的处理" class="toc-sidebar-link">时区的处理</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#与传统日期处理的转换" class="toc-sidebar-link">与传统日期处理的转换</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#jdk注解" class="toc-sidebar-link">JDK注解</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#jdk5中的注解" class="toc-sidebar-link">JDK5中的注解</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java8中的注解" class="toc-sidebar-link">Java8中的注解</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java8对注解的增强" class="toc-sidebar-link">Java8对注解的增强</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#写在最后" class="toc-sidebar-link">写在最后</a><ul class="toc-sidebar-sub-headers"></ul></li></ul></div></div></div></div></div> <div class="option-box-toc-over"><img src="/images/system/toc.png" class="nozoom"> <span class="show-txt">目录</span> <div class="toc-container"><div class="pos-box"><div class="icon-arrow"></div> <div class="scroll-box" style="max-height:550px"><div style="font-weight:bold;text-align:center;">Java8新特性总结</div> <hr> <div class="toc-box"><ul class="toc-sidebar-links"><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java8有哪些新特性" class="toc-sidebar-link">Java8有哪些新特性？</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java8有哪些优点" class="toc-sidebar-link">Java8有哪些优点？</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#lambda表达式" class="toc-sidebar-link">Lambda表达式</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#什么是lambda表达式" class="toc-sidebar-link">什么是Lambda表达式？</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#匿名内部类" class="toc-sidebar-link">匿名内部类</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#lambda表达式-2" class="toc-sidebar-link">Lambda表达式</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#对比常规方法和lambda表达式" class="toc-sidebar-link">对比常规方法和Lambda表达式</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#匿名类到lambda表达式" class="toc-sidebar-link">匿名类到Lambda表达式</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#lambda表达式的语法" class="toc-sidebar-link">Lambda表达式的语法</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#函数式接口" class="toc-sidebar-link">函数式接口</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#lambda表达式典型案例" class="toc-sidebar-link">Lambda表达式典型案例</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#案例一" class="toc-sidebar-link">案例一</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#案例二" class="toc-sidebar-link">案例二</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#案例三" class="toc-sidebar-link">案例三</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#函数式接口总览" class="toc-sidebar-link">函数式接口总览</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#四大核心函数式接口总览" class="toc-sidebar-link">四大核心函数式接口总览</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#其他函数接口总览" class="toc-sidebar-link">其他函数接口总览</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#四大核心函数式接口" class="toc-sidebar-link">四大核心函数式接口</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#consumer接口" class="toc-sidebar-link">Consumer接口</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#supplier接口" class="toc-sidebar-link">Supplier接口</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#function接口" class="toc-sidebar-link">Function接口</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#predicate接口" class="toc-sidebar-link">Predicate接口</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java7与java8中的hashmap" class="toc-sidebar-link">Java7与Java8中的HashMap</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#jdk8-hashmap重排序" class="toc-sidebar-link">JDK8 HashMap重排序</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#筛选与切片" class="toc-sidebar-link">筛选与切片</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#中间操作" class="toc-sidebar-link">中间操作</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#终止操作" class="toc-sidebar-link">终止操作</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#归约" class="toc-sidebar-link">归约</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#optional-容器类" class="toc-sidebar-link">Optional 容器类</a><ul class="toc-sidebar-sub-headers"></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#方法引用与构造器引用" class="toc-sidebar-link">方法引用与构造器引用</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#方法引用" class="toc-sidebar-link">方法引用</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#构造器引用" class="toc-sidebar-link">构造器引用</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#数组引用" class="toc-sidebar-link">数组引用</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java8中的stream" class="toc-sidebar-link">Java8中的Stream</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#什么是stream" class="toc-sidebar-link">什么是Stream?</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream操作的三个步骤" class="toc-sidebar-link">Stream操作的三个步骤</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#如何创建stream" class="toc-sidebar-link">如何创建Stream?</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream的中间操作" class="toc-sidebar-link">Stream的中间操作</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream-的终止操作" class="toc-sidebar-link">Stream 的终止操作</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#并行流与串行流" class="toc-sidebar-link">并行流与串行流</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#fork-join-框架" class="toc-sidebar-link">Fork/Join 框架</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream概述" class="toc-sidebar-link">Stream概述</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#何为stream" class="toc-sidebar-link">何为Stream?</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream操作步骤" class="toc-sidebar-link">Stream操作步骤</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#如何创建stream流" class="toc-sidebar-link">如何创建Stream流？</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream的中间操作-2" class="toc-sidebar-link">Stream的中间操作</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#筛选与切片-2" class="toc-sidebar-link">筛选与切片</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#映射" class="toc-sidebar-link">映射</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#排序" class="toc-sidebar-link">排序</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#stream的终止操作" class="toc-sidebar-link">Stream的终止操作</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#查找与匹配" class="toc-sidebar-link">查找与匹配</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#规约" class="toc-sidebar-link">规约</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#收集" class="toc-sidebar-link">收集</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#如何收集stream流" class="toc-sidebar-link">如何收集Stream流？</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#什么是并行流" class="toc-sidebar-link">什么是并行流？</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#fork-join-框架-2" class="toc-sidebar-link">Fork/Join 框架</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#fork-join-框架与传统线程池有啥区别" class="toc-sidebar-link">Fork/Join 框架与传统线程池有啥区别？</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#fork-join框架实例" class="toc-sidebar-link">Fork/Join框架实例</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java8中的并行流实例" class="toc-sidebar-link">Java8中的并行流实例</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#optional类" class="toc-sidebar-link">Optional类</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#什么是optional类" class="toc-sidebar-link">什么是Optional类？</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#optional类示例" class="toc-sidebar-link">Optional类示例</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#默认方法" class="toc-sidebar-link">默认方法</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#接口中的默认方法" class="toc-sidebar-link">接口中的默认方法</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#默认方法的原则" class="toc-sidebar-link">默认方法的原则</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#接口中的静态方法" class="toc-sidebar-link">接口中的静态方法</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#本地时间和时间戳" class="toc-sidebar-link">本地时间和时间戳</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#使用-localdate、-localtime、-localdatetime" class="toc-sidebar-link">使用 LocalDate、 LocalTime、 LocalDateTime</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#instant-时间戳" class="toc-sidebar-link">Instant 时间戳</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#duration-和-period" class="toc-sidebar-link">Duration 和 Period</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#日期的操纵" class="toc-sidebar-link">日期的操纵</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#解析与格式化" class="toc-sidebar-link">解析与格式化</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#时区的处理" class="toc-sidebar-link">时区的处理</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#与传统日期处理的转换" class="toc-sidebar-link">与传统日期处理的转换</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#jdk注解" class="toc-sidebar-link">JDK注解</a><ul class="toc-sidebar-sub-headers"><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#jdk5中的注解" class="toc-sidebar-link">JDK5中的注解</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java8中的注解" class="toc-sidebar-link">Java8中的注解</a></li><li class="toc-sidebar-sub-header"><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#java8对注解的增强" class="toc-sidebar-link">Java8对注解的增强</a></li></ul></li><li><a href="/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html#写在最后" class="toc-sidebar-link">写在最后</a><ul class="toc-sidebar-sub-headers"></ul></li></ul></div></div></div></div></div> <div class="option-box"><img src="/images/system/wechat.png" class="nozoom"> <span class="show-txt">手机看</span> <div class="toc-container"><div class="pos-box"><div class="icon-arrow"></div> <div class="scroll-box" style="text-align:center"><span style="font-size:0.9rem">微信扫一扫</span> <img height="180px" src="https://api.qrserver.com/v1/create-qr-code/?data=https://binghe001.github.io/md/core/java/java8/2022-04-01-001-Java8%E6%96%B0%E7%89%B9%E6%80%A7%E6%80%BB%E7%BB%93.html" style="margin:10px;">
                可以<b>手机看</b>或分享至<b>朋友圈</b></div></div></div></div> <div class="option-box"><img src="/images/system/toggle.png" width="30px" class="nozoom"> <span class="show-txt">左栏</span></div> <div class="option-box"><img src="/images/system/xingqiu.png" width="25px" class="nozoom"> <span class="show-txt">星球</span> <div class="toc-container"><div class="pos-box"><div class="icon-arrow"></div> <div class="scroll-box" style="text-align:center"><span style="font-size:0.8rem;font-weight:bold;">实战项目<span style="font-size:8px;color:red;">「SpringCloud Alibaba实战项目」</span>、专属电子书、问题解答、简历指导、技术分享、晋升指导、视频课程</span> <img height="180px" src="/images/personal/xingqiu.png" style="margin:10px;"> <b>知识星球</b>：冰河技术
            </div></div></div></div> <div class="option-box"><img src="/images/system/wexin4.png" width="25px" class="nozoom"> <span class="show-txt">读者群</span> <div class="toc-container"><div class="pos-box"><div class="icon-arrow"></div> <div class="scroll-box" style="text-align:center"><span style="font-size:0.8rem;font-weight:bold;">添加冰河微信<span style="color:red;">(hacker_binghe)</span>进冰河技术学习交流圈「无任何套路」</span> <img src="/images/personal/hacker_binghe.jpg" height="180px" style="margin:10px;">
                PS：添加时请备注<b>读者加群</b>，谢谢！
              </div></div></div></div> <div class="option-box"><img src="/images/system/download-2.png" width="25px" class="nozoom"> <span class="show-txt">下资料</span> <div class="toc-container"><div class="pos-box"><div class="icon-arrow"></div> <div class="scroll-box" style="text-align:center"><span style="font-size:0.8rem;font-weight:bold;">扫描公众号，回复<span style="color:red;">“1024”</span>下载<span style="color:red;">100GB+</span>学习技术资料、PDF书籍、实战项目、简历模板等「无任何套路」</span> <img src="/images/personal/qrcode.png" height="180px" style="margin:10px;"> <b>公众号:</b> 冰河技术
              </div></div></div></div> <div class="option-box"><img src="/images/system/heart-1.png" width="25px" class="nozoom"> <span class="show-txt">赞赏我</span> <div class="toc-container"><div class="pos-box"><div class="icon-arrow"></div> <div class="scroll-box" style="text-align:center"><span style="font-size:0.8rem;font-weight:bold;">鼓励/支持/赞赏我</span> <img height="180px" src="/images/personal/encourage-head.png" style="margin:5px;"> <br>1. 不靠它生存但仍希望得到你的鼓励；
                <br>2. 时刻警醒自己保持技术人的初心；
              </div></div></div></div> <div title="重复注解与类型注解，你真的学会了吗？" class="option-box" style="padding-left:2px;text-align:center;"><a href="/md/core/java/java8/2022-03-31-016-重复注解与类型注解，你真的学会了吗.html"><img src="/images/system/pre2.png" width="30px" class="nozoom"> <span class="show-txt">上一篇</span></a></div> <!----></div>  <!----> </aside></div><div class="global-ui"><div class="read-more-wrap" style="display:none;position:absolute;bottom:0px;z-index:9999;width:100%;margin-top:-100px;font-family:PingFangSC-Regular, sans-serif;"><div id="read-more-mask" style="position: relative; height: 200px; background: -webkit-gradient(linear, 0 0%, 0 100%, from(rgba(255, 255, 255, 0)), to(rgb(255, 255, 255)));"></div> <a id="read-more-btn" target="_self" style="position: absolute; left: 50%; top: 70%; bottom: 30px; transform: translate(-50%, -50%); width: 160px; height: 36px; line-height: 36px; font-size: 15px; text-align: center; border: 1px solid rgb(222, 104, 109); color: rgb(222, 104, 109); background: rgb(255, 255, 255); cursor: pointer; border-radius: 6px;">阅读全文</a> <div id="btw-modal-wrap" style="display: none;"><div id="btw-mask" style="position: fixed; top: 0px; right: 0px; bottom: 0px; left: 0px; opacity: 0.7; z-index: 999; background: rgb(0, 0, 0);"></div> <div id="btw-modal" style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 300px; text-align: center; font-size: 13px; background: rgb(255, 255, 255); border-radius: 10px; z-index: 9999; font-family: PingFangSC-Regular, sans-serif;"><span id="btw-modal-close-btn" style="position: absolute; top: 5px; right: 15px; line-height: 34px; font-size: 34px; cursor: pointer; opacity: 0.2; z-index: 9999; color: rgb(0, 0, 0); background: none; border: none; outline: none;">×</span> <p id="btw-modal-header" style="margin-top: 40px; line-height: 1.8; font-size: 13px;">
                扫码或搜索：<span style="color: #E9405A; font-weight: bold;">冰河技术</span> <br>发送：<span id="fustack-token" class="token" style="color: #e9415a; font-weight: bold; font-size: 17px; margin-bottom: 45px;">290992</span> <br>即可<span style="color: #e9415a; font-weight: bold;">立即永久</span>解锁本站全部文章</p> <img src="/images/personal/qrcode.png" style="width: 180px; margin-top: 10px; margin-bottom: 30px; border: 8px solid rgb(230, 230, 230);"></div></div></div><div class="pay-read-more-wrap" style="display:none;position:absolute;bottom:0px;z-index:9999;width:100%;margin-top:-100px;font-family:PingFangSC-Regular, sans-serif;"><div id="pay-read-more-mask" style="position: relative; height: 200px; background: -webkit-gradient(linear, 0 0%, 0 100%, from(rgba(255, 255, 255, 0)), to(rgb(255, 255, 255)));"></div> <a id="pay-read-more-btn" target="_blank" style="position: absolute; left: 50%; top: 70%; bottom: 30px; transform: translate(-50%, -50%); width: 160px; height: 36px; line-height: 36px; font-size: 15px; text-align: center; border: 1px solid rgb(222, 104, 109); color: rgb(222, 104, 109); background: rgb(255, 255, 255); cursor: pointer; border-radius: 6px;">付费阅读</a></div></div></div>
    <script src="/assets/js/cg-styles.js?v=1653305936337" defer></script><script src="/assets/js/cg-4.js?v=1653305936337" defer></script><script src="/assets/js/cg-3.js?v=1653305936337" defer></script><script src="/assets/js/cg-64.js?v=1653305936337" defer></script><script src="/assets/js/cg-5.js?v=1653305936337" defer></script><script src="/assets/js/cg-6.js?v=1653305936337" defer></script><script src="/assets/js/cg-app.js?v=1653305936337" defer></script>
  </body>
</html>
